﻿
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports fhtPrint.fhtPrint.fhtPrint
Imports IDServer



Public Class Frm_SALRetailSC
    Implements IDServer.IDServer.IDServer


    Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp
    Private mDatasetA As DataSet
    Private mDatasetB As DataSet
    Private mDatasetC As DataSet
    Private mDataset As DataSet
    Private GoodsSalePrice As Double
    Private DSSalesPromotion As DataSet
    Private DSMember As DataSet
    Private GifDataSet As DataSet
    Private IsOutPut As Boolean
    Private mTableA As DataTable
    Private mTable As DataTable
    Private dsGoods As DataSet
    Private M_Ds As DataSet
    Private TreeDs As DataSet
    Private CustomerDS As DataSet
    Private Fields As String
    Private OldCellValue As String
    Private RowIndex As Integer
    Private NewValue As Integer
    Private OldValue As Integer
    Private mPoint As Point
    Private bFind As Boolean
    Private X, Y As Integer
    Private WithEvents ComBox As New ComboBox
    Private WithEvents MainForm As Frm_MainForm



    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainForm
        End Get
        Set(ByVal value As Frm_MainForm)
            MainForm = value
        End Set
    End Property



#Region "inteface define"

    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd
        If AddEnable = False Then
            MessageBox.Show(My.resources.notallowadd, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If

        Me.TabControl1.SelectedIndex = 1
        SetEnable(True)
        ClearText()
        ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd
        MainForm.BtnEnable(False)
        Me.cbmCustomeType.SelectedIndex = 0
        Me.txtWriteNo.Focus()
        Me.txtzhekou.Text = ""
        Me.TextBoxShow.Text = ""
        Me.txtCustomer.Text = ""
        ClearText()
        Me.NumericUpDown1.Value = 100
        Me.txtSaleDate.Value = Date.Now.ToString("yyyy-MM-dd")
        Me.cmbInvType.SelectedValue = "DEPOSIT"
        Me.DGV_Detail.AllowUserToAddRows = True
    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel
        Me.ComboBox1.Enabled = False
        SetEnable(False)
        ClearText()
        ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
        If Me.TabControl1.SelectedIndex = 0 Then

        Else
            Me.DGV_Detail.AllowUserToAddRows = False
            If mDatasetA.Tables(0).Rows.Count <= 0 Then
                bFind = False
                If Not Me.DGV_Detail.DataSource Is Nothing Then
                    CType(Me.DGV_Detail.DataSource, DataTable).Rows.Clear()
                End If
            Else
                bFind = True
                FillText(Me.DGV_Master.CurrentRow.Cells("fSaleOrdeNo").Value)
            End If
        End If

        MainForm.BtnEnable(bFind)
        SetToolEnable()
    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete

        Try
            If DeleteEnable = False Then
                MessageBox.Show(My.Resources.NotAllowDelete, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            If Me.DGV_Master.CurrentRow Is Nothing Then
                Return True
            End If
            Dim SaleOrdeNo As String = Me.DGV_Master.CurrentRow.Cells("fSaleOrdeNo").Value
            If SaleOrdeNo.Length <= 0 Then
                Exit Function
            End If
            If MsgBox(My.resources.ConfirmDelete, MsgBoxStyle.Question + MsgBoxStyle.OkCancel, Msg.CompanyName) = MsgBoxResult.Ok Then
                If DeleteFromDataBase(SaleOrdeNo) = True Then
                    MsgBox(My.Resources.DeleteSuccess, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    If Not Me.DGV_Master.CurrentRow Is Nothing Then
                        FillText(Me.DGV_Master.CurrentRow.Cells("fSaleOrdeNo").Value)
                    Else
                        ClearText()
                    End If
                End If

            End If
        Catch ex As Exception
            MsgBox("ActionDelete:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit
        If EditEnable = False Then
            MessageBox.Show(My.resources.NotAllowEidt, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If

        If Me.TabControl1.SelectedIndex = 0 Then
            Me.TabControl1.SelectedIndex = 1
        End If
        SetEnable(True)
        ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit
        MainForm.BtnEnable(False)
    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport
        Select Case Me.TabControl1.SelectedIndex

            Case 0
                ExportToExcel(Me.DGV_Master, PubCompanyName)
            Case 1
                'PrintInStoreNumDetail(Me.DGV_Detail, Me.LabInfo.Text, Me.cbInStoreType.Text, Me.cbToStore.Text, Me.cbFromStore.Text, Me.LabOperateDate.Text, Me.txtDeliverNo.Text, Me.txtDeliverPerson.Text, Me.txtDeliverDate.Text, "", 0)
        End Select
    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter
        Dim Frm_Filter As New Frm_Filter
        Me.Cursor = Cursors.WaitCursor
        Frm_Filter.LoadHeaderCaption(Fields, "Frm_SALRetailSC")
        Frm_Filter.ShowDialog()
        Me.Cursor = Cursors.Default
        ReBindGridCaption(Me.DGV_Master, "Frm_SALRetailSC")
    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

        Try
            Me.DGV_Master.CurrentCell = Me.DGV_Master.Rows(0).Cells(0)
            MainForm.ToolStripFirst.Enabled = False
            MainForm.ToolStripNext.Enabled = True
            MainForm.ToolStripPrivous.Enabled = False
            MainForm.ToolStripLast.Enabled = True
            Dim fCode As String = Me.DGV_Master.CurrentRow.Cells("fSaleOrdeNo").Value
            If fCode.Length > 0 Then
                FillText(fCode)
            End If

        Catch ex As Exception
            MsgBox("ActionGoFirst:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

        Try
            Me.DGV_Master.CurrentCell = Me.DGV_Master.Rows(Me.DGV_Master.RowCount - 1).Cells(0)
            MainForm.ToolStripFirst.Enabled = True
            MainForm.ToolStripNext.Enabled = False
            MainForm.ToolStripPrivous.Enabled = True
            MainForm.ToolStripLast.Enabled = False
            Dim fCode As String = Me.DGV_Master.CurrentRow.Cells("fSaleOrdeNo").Value
            If fCode.Length > 0 Then
                FillText(fCode)
            End If

        Catch ex As Exception
            MsgBox("ActionGoFirst:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try


    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

        Try
            Me.DGV_Master.CurrentCell = Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index + 1).Cells(0)
            If Me.DGV_Master.CurrentRow.Index = Me.DGV_Master.RowCount - 1 Then
                MainForm.ToolStripNext.Enabled = False
                MainForm.ToolStripLast.Enabled = False
            Else
                MainForm.ToolStripPrivous.Enabled = True
                MainForm.ToolStripLast.Enabled = True
                MainForm.ToolStripFirst.Enabled = True
                MainForm.ToolStripNext.Enabled = True
            End If
            Dim fCode As String = Me.DGV_Master.CurrentRow.Cells("fSaleOrdeNo").Value
            If fCode.Length > 0 Then
                FillText(fCode)
            End If

        Catch ex As Exception
            MsgBox("ActionGoNext:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try


    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

        Try
            Me.DGV_Master.CurrentCell = Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index - 1).Cells(0)
            If Me.DGV_Master.CurrentRow.Index = 0 Then
                MainForm.ToolStripFirst.Enabled = False
                MainForm.ToolStripPrivous.Enabled = False
            Else
                MainForm.ToolStripFirst.Enabled = True
                MainForm.ToolStripNext.Enabled = True
                MainForm.ToolStripPrivous.Enabled = True
                MainForm.ToolStripLast.Enabled = True
            End If
            Dim fCode As String = Me.DGV_Master.CurrentRow.Cells("fSaleOrdeNo").Value
            If fCode.Length > 0 Then
                FillText(fCode)
            End If

        Catch ex As Exception
            MsgBox("ActionGoPrevious:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try


    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport
        Try

        Catch ex As Exception
            MsgBox("ActionImport:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

        Try
            Dim NewTable As DataTable = CType(Me.DGV_Detail.DataSource, DataTable)


            If isNull(Me.txtArea.Text) Then
                MsgBox("區域不能為空！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Return False
            End If


            If NewTable.Rows.Count <= 0 Then
                MsgBox("訂購貨品不能為空，請選擇貨品！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Me.DGV_Detail.Focus()
                Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(0).Cells("fGoodsBarCode")
                Return False
            End If
            For i As Integer = 0 To NewTable.Rows.Count - 1
                If NewTable.Rows(i).Item("fSumCount") Is DBNull.Value OrElse isNull(NewTable.Rows(i).Item("fSumCount").ToString) Then
                    MsgBox("第 [ " & i + 1 & " ] 行數量不能為空！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(i).Cells("fSumCount")
                    Return False
                End If
            Next
            If Me.cbmCustomeType.SelectedValue = "Retail" Then
                If Me.cbmCustomeType.Text.Length <= 0 Then
                    MsgBox("客戶類型不能為空！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Me.cbmCustomeType.Focus()
                    SendKeys.Send("{F4}")
                    Return False
                End If

                If Me.CBDeliverMode.SelectedIndex < 0 Then
                    MsgBox("送貨方式不能為空！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Me.CBDeliverMode.Focus()
                    SendKeys.Send("{F4}")
                    Return False
                End If
                If Me.CBDeliverMode.SelectedIndex = 0 Then
                    If Me.ComboBox1.SelectedIndex < 0 Then
                        MsgBox("到取門市不能為空！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        Me.ComboBox1.Focus()
                        SendKeys.Send("{F4}")
                        Return False
                    End If
                End If
            End If

            If Format(DateTimePicker1.Value, "yyyy-MM-dd") < ServerDate Then
                MessageBox.Show("送貨日期不能小於當前日期。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Me.DateTimePicker1.Focus()
                Return False
            End If

            If Me.txtActualAmount.Text.Length <= 0 Then
                MsgBox("實收訂金不能為空！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Me.txtActualAmount.Focus()
                Return False
            Else

                If Me.txtSumDSI.Text.Length <= 0 Or _
(Me.cbmCustomeType.SelectedValue.ToString.Equals("Retail", StringComparison.InvariantCultureIgnoreCase) _
And Me.txtSumDSI.Text = "0.00") Then
                    MsgBox("實收金額不能為空！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Me.DGV_PayMode.Focus()
                    Me.DGV_PayMode.CurrentCell = Me.DGV_PayMode.Rows(0).Cells(3)
                    Return False
                End If

                If (Me.cbmCustomeType.SelectedValue.ToString.Equals("Retail", StringComparison.InvariantCultureIgnoreCase) _
And Convert.ToDouble(Me.txtSumDSIA.Text) > Convert.ToDouble(Me.txtActualAmount.Text)) Then
                    MsgBox("應付訂金不足，不能存檔！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Me.txtActualAmount.Focus()
                    Return False
                End If

                If (Me.cbmCustomeType.SelectedValue.ToString.Equals("Retail", StringComparison.InvariantCultureIgnoreCase) _
And Convert.ToDouble(Me.txtSumDSI.Text) < Convert.ToDouble(Me.txtActualAmount.Text)) Then
                    MsgBox("應付金額不足，不能存檔！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Me.DGV_PayMode.Focus()
                    Me.DGV_PayMode.CurrentCell = Me.DGV_PayMode.Rows(0).Cells(3)
                    Return False
                End If
            End If

            If (Val(Me.txtActualAmount.Text) > (Me.txtFTAmount.Text)) Then
                MessageBox.Show("實收計金大於貨品總金額，是否確定要保存。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Me.txtActualAmount.Focus()
                Return False
            End If

            'If (Val(Me.txtSumDSI.Text) - Val(Me.txtActualAmount.Text)) <> Val(Me.txtBalanse.Text) Then
            '    MessageBox.Show("實收訂金或者實收金額錄入不正確。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
            '    Me.DGV_PayMode.Focus()
            '    Return False
            'End If

            Return True
        Catch ex As Exception
            MsgBox("ActionInitialize:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

        Dim m_Ds As New DataSet
        Try
            If mDatasetB.Tables(0).Rows.Count <= 0 Then
                MsgBox("對不起，沒有數據可列印！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Exit Function
            End If
            If Me.TabControl1.SelectedIndex <> 1 Then
                Exit Function
            End If


            '把總金額轉換成大寫
            Dim RTC As String = CapitalRMB(Format(mDatasetB.Tables(0).Compute("sum(fSumMoney)", ""), "#0.00"))

            Dim Pathstr As String = ""
            Dim ConfigNode() As String = ReadConfigFile.Split(";")
            Dim CheckMan As String = ""
            Dim CheckDate As String = ""
            Dim mServer As String = ""
            Dim mDataBase As String = ""
            Dim mUserID As String = ""
            Dim mPassword As String = ""
            Dim sql As String = ""
            Dim SaleOrdeNo As String = Me.LabOrdingNo.Text

            sql = "select * from BSC_Dept where fCode='" & PubCompanyCode & "';"
            sql += "  select fcustomerName,fdeliveraddress,fLinkPhone,a.fsaleordeno,fsaledate, "
            sql += "  isnull(FCName,'')as FCName,isnull(fAddress,'')as fAddress, "
            sql += "  isnull(fPhone,'')as fPhone,isnull(fFax,'')as fFax, "
            sql += "  isnull(fBank,'') as fBank,isnull(fAccount,'')as fAccount,isnull(fCorporation,'')as fCorporation,   "
            sql += "  Origin, TransportMode, paymentMethod, PortOfLoading, PortOfDestination, Packing, Buyer, Saller, "
            sql += " Insurance, claims, Arbitration, ForceMajeure, SourceDocPath, ShippingMarks,QtyPriceAmount,SelModeOther,Other "
            sql += "  from Sal_SaleOrdea a "
            sql += "  left join BSC_DEPT b on a.shopno = b.fcode "
            sql += "  left join Sal_SaleOrdeD c on a.fsaleordeno = c.fsaleordeno "
            sql += "  where a.fsaleordeno = '" & SaleOrdeNo & "' "


            m_Ds = ReturnDataset(sql)

            'If Me.DGV_Detail.Columns("PoNum").Visible = True Then
            '    Pathstr = GetReportPath("InStore", "RepInStore1.rpt")
            'Else
            If Me.cbmCustomeType.SelectedValue = "Retail" Then '如果是零售
                Pathstr = GetReportPath("SAL", "RepSaleInv.rpt")
            Else
                Pathstr = GetReportPath("SAL", "SaleOrdePrint.rpt")
            End If
            'End If     

            'If Me.DGV_Master.CurrentRow.Cells("CheckPerson").Value Is DBNull.Value Then
            '    CheckMan = ""
            'Else
            '    CheckMan = Me.DGV_Master.CurrentRow.Cells("CheckPerson").Value
            'End If
            'If Me.DGV_Master.CurrentRow.Cells("CheckDate").Value Is DBNull.Value Then
            '    CheckDate = ""
            'Else
            '    CheckDate = Me.DGV_Master.CurrentRow.Cells("CheckDate").Value
            'End If
            For i As Integer = 0 To ConfigNode.Length - 1
                If ConfigNode(i).Split("=")(0).ToLower = "Server".ToLower Then
                    mServer = ConfigNode(i).Split("=")(1)
                End If
                If ConfigNode(i).Split("=")(0).ToLower = "DataBase".ToLower Then
                    mDataBase = ConfigNode(i).Split("=")(1)
                End If
                If ConfigNode(i).Split("=")(0).ToLower = "Uid".ToLower Then
                    mUserID = ConfigNode(i).Split("=")(1)
                End If
                If ConfigNode(i).Split("=")(0).ToLower = "Pwd".ToLower Then
                    mPassword = ConfigNode(i).Split("=")(1)
                End If
            Next

            Dim myReportDoc As New CrystalDecisions.CrystalReports.Engine.ReportDocument
            Dim myParameterValues As New CrystalDecisions.Shared.ParameterValues
            Dim myDiscreteValue As New CrystalDecisions.Shared.ParameterDiscreteValue

            Dim logonInfo As New CrystalDecisions.Shared.TableLogOnInfo
            Dim table As CrystalDecisions.CrystalReports.Engine.Table
            myReportDoc.Load(Pathstr)

            For Each table In myReportDoc.Database.Tables
                logonInfo = table.LogOnInfo
                With logonInfo.ConnectionInfo
                    .ServerName = mServer
                    .DatabaseName = mDataBase
                    .UserID = mUserID
                    .Password = mPassword
                End With
                table.ApplyLogOnInfo(logonInfo)
            Next

            If Me.cbmCustomeType.SelectedValue = "Retail" Then '如果是零售
                If mDatasetB.Tables(0).Rows.Count > 0 Then
                    myReportDoc.SetDataSource(CType(Me.DGV_Detail.DataSource, DataTable))
                    myReportDoc.SetParameterValue("ShopAddress", m_Ds.Tables(0).Rows(0).Item("fAddress") & "")
                    myReportDoc.SetParameterValue("ShopName", m_Ds.Tables(0).Rows(0).Item("fCName") & "")
                    myReportDoc.SetParameterValue("ShopPhone", m_Ds.Tables(0).Rows(0).Item("fPhone") & "")
                    myReportDoc.SetParameterValue("CustomePhone", "")
                    myReportDoc.SetParameterValue("DeliverPhone", "")
                    myReportDoc.SetParameterValue("fSaleOrdeNo", Me.LabOrdingNo.Text)
                    myReportDoc.SetParameterValue("fSaleInvNo", Me.LabInvNo.Text)
                    myReportDoc.SetParameterValue("CustomeName", Me.txtCustomer.Text)
                    myReportDoc.SetParameterValue("LinkMan", Me.txtReciveman.Text)
                    myReportDoc.SetParameterValue("LinePhone", Me.txtCustomePhone.Text)
                    myReportDoc.SetParameterValue("DeliverAddress", Me.txtArea.Text & Me.txtDliveraddress.Text)
                    myReportDoc.SetParameterValue("OrdeType", Me.cmbDept.Text)
                    myReportDoc.SetParameterValue("WriteNo", Me.txtWriteNo.Text)
                    myReportDoc.SetParameterValue("SaleDate", Me.txtSaleDate.Value)
                    myReportDoc.SetParameterValue("SaleMan", Me.CBSaleman.Text)
                    myReportDoc.SetParameterValue("OperateMan", PubUserCode)
                End If
            Else
                myReportDoc.SetDataSource(CType(Me.DGV_Detail.DataSource, DataTable))
                myReportDoc.SetParameterValue("Buyers", m_Ds.Tables(1).Rows(0).Item("fcustomerName") & "")
                myReportDoc.SetParameterValue("Address", m_Ds.Tables(1).Rows(0).Item("fdeliveraddress") & "")
                myReportDoc.SetParameterValue("Tel", m_Ds.Tables(1).Rows(0).Item("fLinkPhone") & "")
                myReportDoc.SetParameterValue("Sellers", m_Ds.Tables(1).Rows(0).Item("FCName") & "")
                myReportDoc.SetParameterValue("Address1", m_Ds.Tables(1).Rows(0).Item("fAddress") & "")
                myReportDoc.SetParameterValue("Tel1", m_Ds.Tables(1).Rows(0).Item("fPhone") & "")
                myReportDoc.SetParameterValue("Fax1", m_Ds.Tables(1).Rows(0).Item("fFax") & "")
                myReportDoc.SetParameterValue("fBank", m_Ds.Tables(1).Rows(0).Item("fBank") & "")
                myReportDoc.SetParameterValue("fAccount", m_Ds.Tables(1).Rows(0).Item("fAccount") & "")
                myReportDoc.SetParameterValue("fCorporation", m_Ds.Tables(1).Rows(0).Item("fCorporation") & "")
                myReportDoc.SetParameterValue("fSaleOrdeNo", m_Ds.Tables(1).Rows(0).Item("fsaleordeno") & "")
                myReportDoc.SetParameterValue("fsaledate", m_Ds.Tables(1).Rows(0).Item("fsaledate") & "")
                myReportDoc.SetParameterValue("Signedat", m_Ds.Tables(1).Rows(0).Item("Buyer") & "")
                myReportDoc.SetParameterValue("Packing", m_Ds.Tables(1).Rows(0).Item("Packing") & "")
                myReportDoc.SetParameterValue("ShippingMarks", m_Ds.Tables(1).Rows(0).Item("ShippingMarks") & "")
                myReportDoc.SetParameterValue("Loadingport", m_Ds.Tables(1).Rows(0).Item("PortOfLoading") & "")
                myReportDoc.SetParameterValue("Destination", m_Ds.Tables(1).Rows(0).Item("PortOfDestination") & "")
                myReportDoc.SetParameterValue("Timeofshipment", m_Ds.Tables(1).Rows(0).Item("Saller") & "")
                myReportDoc.SetParameterValue("Termsofpayment", Me.CBSelMode.Text)
                myReportDoc.SetParameterValue("Insurance", m_Ds.Tables(1).Rows(0).Item("Insurance") & "")
                myReportDoc.SetParameterValue("Remarks", Me.txtCustomeRemark.Text)
                myReportDoc.SetParameterValue("RTC", RTC)
                myReportDoc.SetParameterValue("SelModeOther", m_Ds.Tables(1).Rows(0).Item("SelModeOther") & "")
                myReportDoc.SetParameterValue("txtQtyPriceAmount", m_Ds.Tables(1).Rows(0).Item("QtyPriceAmount") & "")
                myReportDoc.SetParameterValue("Other", m_Ds.Tables(1).Rows(0).Item("Other") & "")



            End If

            My.Forms.Frm_Report.CrystalReportViewer1.ReportSource = myReportDoc
            My.Forms.Frm_Report.CrystalReportViewer1.Zoom(1)
            My.Forms.Frm_Report.CrystalReportViewer1.DisplayGroupTree = False

            Frm_Report.ShowDialog()

        Catch ex As Exception
            MsgBox("對不起，打印出錯！" & ex.Message & ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave
        BtnActionSave()

    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function

    Public Function ActionChecked() As Boolean

        Try
            If CheckEnable = False Then
                MessageBox.Show("對不起，您沒有審核權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            Dim sql As String = ""
            Dim CheckDate As String = ReturnServerDate()
            Dim SaleOrdeNo As String = Me.DGV_Master.CurrentRow.Cells("fSaleOrdeNo").Value
            If SaleOrdeNo.Length <= 0 Then Exit Function
            If MsgBox(My.resources.ComfirmChecked, MsgBoxStyle.Question + MsgBoxStyle.YesNo, Msg.CompanyName) = MsgBoxResult.Yes Then
                sql = "Update Sal_SaleOrdeA set fOrdeStatus='B',fCheckMan='" & PubUserName & "',fCheckDate='" & CheckDate & "',fCheckComputer='" & My.Computer.Name & "' where fSaleOrdeNo='" & SaleOrdeNo & "';"
                sql += "Update Sal_InvoiceA set BillstatusID='B',CheckDate='" & CheckDate & "',CheckComputer='" & My.Computer.Name & "',Checkby='" & PubUserName & "' where FSaleOrdeNo='" & SaleOrdeNo & "'"
                ReturnObject(sql)
                Dim Rows() As DataRow = mDatasetA.Tables(0).Select("fSaleOrdeNo='" & SaleOrdeNo & "'")
                If Rows.Length > 0 Then
                    Rows(0).Item("fOrdeStatus") = "核准"
                    Rows(0).Item("fCheckMan") = PubUserName
                    Rows(0).Item("fCheckDate") = CheckDate
                End If
                mDatasetA.AcceptChanges()
                Me.DGV_Master.DataSource = mDatasetA.Tables(0)
                SetGridRowBackColor(Me.DGV_Master, mDatasetA)
                MsgBox("審核成功，谢谢！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            End If
        Catch ex As Exception
            MsgBox("ActionChecked:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    Public Function ActionUnchecked() As Boolean

        Try
            If UncheckEnable = False Then
                MessageBox.Show("對不起，您沒有反審核權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            Dim sql As String = ""
            Dim CheckDate As String = ReturnServerDate()
            Dim SaleOrdeNo As String = Me.DGV_Master.CurrentRow.Cells("fSaleOrdeNo").Value
            If SaleOrdeNo.Length <= 0 Then Exit Function
            If MsgBox(My.resources.ComfirmUnchecked, MsgBoxStyle.Question + MsgBoxStyle.YesNo, Msg.CompanyName) = MsgBoxResult.Yes Then
                sql = "Update Sal_SaleOrdeA set fOrdeStatus='C',fUnCheckMan='" & PubUserName & "',fUnCheckDate='" & CheckDate & "',fUnCheckComputer='" & My.Computer.Name & "' where fSaleOrdeNo='" & SaleOrdeNo & "'"
                ReturnObject(sql)
                Dim Rows() As DataRow = mDatasetA.Tables(0).Select("fSaleOrdeNo='" & SaleOrdeNo & "'")
                If Rows.Length > 0 Then
                    Rows(0).Item("fOrdeStatus") = "反核准"
                    Rows(0).Item("fCheckMan") = PubUserName
                    Rows(0).Item("fCheckDate") = CheckDate
                End If
                mDatasetA.AcceptChanges()
                Me.DGV_Master.DataSource = mDatasetA.Tables(0)
                SetGridRowBackColor(Me.DGV_Master, mDatasetA)
                MsgBox("反審核成功，謝謝！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            End If
        Catch ex As Exception
            MsgBox("ActionUnchecked:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    Public Function ActionComplete() As Boolean

        Try

        Catch ex As Exception
            MsgBox("ActionComplete:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

#End Region


#Region "sub or function"


    ''' <summary>
    ''' 會員自動升級
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub UpdateMemberMark()
        Dim sql As String = ""
        Try
            Dim Rates As Double = 1.0 ''積分

            If DSMember.Tables(1).Rows.Count > 0 Then
                Dim ConsumeIndex As String = DSMember.Tables(1).Rows(0).Item("Listcode") & ""
                Dim Mark As Double = Convert.ToDouble(DSMember.Tables(1).Rows(0).Item("ListB"))
                If ConsumeIndex.Length > 0 Then
                    If ConsumeIndex = "0" Then
                        Dim ConSumeTime As Double = Convert.ToDouble(DSMember.Tables(1).Rows(0).Item("ListA"))
                        Rates = Mark / ConSumeTime
                        sql = "Update BSC_Customer Set FIntegral= FIntegral+ " & Rates & " where Code='" & Me.CBCustomerNo.Text.Replace("*", "") & "'"
                        ReturnObject(sql)
                    ElseIf ConsumeIndex = "1" Then
                        Dim ConsumeMoney As Double = Val(DSMember.Tables(1).Rows(0).Item("ListA"))
                        If Val(Me.txtFTAmount.Text) >= Val(ConsumeMoney) Then
                            Rates = (Mark / ConsumeMoney) * Val(Me.txtFTAmount.Text)
                            sql = "Update BSC_Customer Set FIntegral= FIntegral +" & Rates & " where Code='" & Me.CBCustomerNo.Text.Replace("*", "") & "'"
                            ReturnObject(sql)
                        End If
                    End If
                End If
            End If
            sql = "select * from BSC_Customer where Code='" & Me.CBCustomerNo.Text.Replace("*", "") & "' ;"
            sql += "select * from BSC_OtherDefineB where ItemNo=17 "
            Dim Ms_Data As New DataSet
            Dim ddcode As String = ""

            Dim fLevel As String = 1
            Ms_Data = ReturnDataset(sql)
            If Not Ms_Data Is Nothing Then
                Dim fMark As Double = Convert.ToDouble(Ms_Data.Tables(0).Rows(0).Item("FIntegral"))
                fLevel = Ms_Data.Tables(0).Rows(0).Item("fLevel") & ""
                For i As Integer = 0 To Ms_Data.Tables(1).Rows.Count - 1
                    Dim Listcode As String = Ms_Data.Tables(1).Rows(i).Item("Listcode") & ""
                    If i = Ms_Data.Tables(1).Rows.Count - 1 Then
                        If fMark >= Convert.ToDouble(Ms_Data.Tables(1).Rows(i).Item("ListC")) Then
                            sql = "Update BSC_Customer Set FLevel='" & Listcode & "' where Code='" & Me.CBCustomerNo.Text & "'"
                            ReturnObject(sql)
                            ddcode = Listcode
                        End If
                    Else
                        If fMark >= Convert.ToDouble(Ms_Data.Tables(1).Rows(i).Item("ListC")) And fMark < Convert.ToDouble(Ms_Data.Tables(1).Rows(i + 1).Item("ListC")) Then
                            sql = "Update BSC_Customer Set FLevel='" & Listcode & "' where Code='" & Me.CBCustomerNo.Text & "'"
                            ReturnObject(sql)
                            ddcode = Listcode
                        End If
                    End If
                Next
            End If

            ''更新會員數據集
            Dim srow() As DataRow = DSMember.Tables(0).Select("code='" & Me.CBCustomerNo.Text.Trim.Replace("*", "") & "'")
            If srow.Length > 0 Then
                srow(0).Item("FIntegral") = Val(srow(0).Item("FIntegral")) + Val(Rates) ''積分
                'If Ms_Data.Tables(1).Rows.Count > 0 Then

                '    Dim ListB As Double = Val(Ms_Data.Tables(1).Rows(1).Item("ListB"))
                '    srow(0).Item("Rat") = ListB ''折扣
                'End If
                Dim ddrow() As DataRow = Ms_Data.Tables(1).Select("Listcode='" & ddcode & "'")
                If ddrow.Length > 0 Then
                    srow(0).Item("Rat") = Val(ddrow(0).Item("ListB")) ''折扣
                End If
            End If
        Catch ex As Exception
            ''  MsgBox("UpdateMemberMark:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    '''  加載會員和積分
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub LoadMemberPerson()
        Try
            Dim ServerDate As String = ReturnServerDate()
            Dim sql As String = ""
            sql += "select a.ID,a.Code,a.Cnname,a.LinkMan,a.CnAddress,a.FType,a.Phone1,a.FLevel,a.FIntegral,b.ListA,b.ListB as Rat from BSC_Customer a left join "
            sql += "(select b.* from dbo.BSC_OtherDefineA a inner join BSC_OtherDefineB b on a.ID=b.ItemNo where a.ItemCode='MemberLevel') b "
            sql += "on a.FLevel=b.ListCode where a.Status=1 and a.FType='Retail'and convert(nvarchar(10),a.stopdate,21)>='" & ServerDate & "';"
            sql += "select a.*,b.* from BSC_OtherDefineA a inner join BSC_OtherDefineB b on a.ID=b.ItemNo where a.ItemCode='MemberDefine'"
            DSMember = New DataSet
            DSMember = ReturnDataset(sql)
        Catch ex As Exception
            MsgBox("LoadMemberPerson:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    ''' Load Gif Set
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub LoadGifSet()
        Dim sql As String
        Try
            sql = "select * from dbo.BSC_Gift where '2007-03-13' between Convert(varchar(10),StartDate,21) and Convert(varchar(10),EndDate,21) and Status=0"
            GifDataSet = ReturnDataset(sql)
        Catch ex As Exception
            MsgBox("LoadGifSet:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub
    ''' <summary>
    ''' 加載促銷設置
    ''' </summary>
    ''' <remarks></remarks>
    ''' 
    Private Sub LoadSalesPromotionSet()
        Try
            Dim sql As String = ""
            'Dim mDate As String = ReturnServerDate()
            sql = "select a.Num,Convert(varchar(10),a.StartDate,21) as StartDate,Convert(varchar(10),a.EndDate,21) as EndDate,a.PromotionType,a.IsSame,a.Dept,a.DisCount as DisCountA,a.Reduce as ReduceA,a.PurQty as PurQtyA,a.Present as PresentA,b.SN,b.BarCode,b.DisCount as DisCountB,b.Reduce as ReduceB,b.PurQty as PurQtyB,b.Present as PresentB,b.GoodsType"
            sql += " from dbo.PUR_PromotionA a inner join PUR_PromotionB b on a.Num=b.Num where  Convert(varchar(10),Getdate(),21)  between Convert(varchar(10),a.Startdate,21) and convert(varchar(10),a.EndDate,21)    and charindex('," & PubCompanyCode & ",',','+Dept+',')>0 "
            'sql = "select a.Num,Convert(varchar(10),a.StartDate,21) as StartDate,Convert(varchar(10),a.EndDate,21) as EndDate,a.PromotionType,a.IsSame,a.Dept,a.DisCount as DisCountA,a.Reduce as ReduceA,a.PurQty as PurQtyA,a.Present as PresentA from PUR_PromotionA a where '" & mDate & "' between Convert(varchar(10),a.Startdate,21) and convert(varchar(10),a.EndDate,21) ;"
            'sql += " select b.Num,b.SN,b.BarCode,b.DisCount as DisCountB,b.Reduce as ReduceB,b.PurQty as PurQtyB,b.Present as PresentB,b.GoodsType from PUR_PromotionB b"
            DSSalesPromotion = New DataSet
            DSSalesPromotion = ReturnDataset(sql)
        Catch ex As Exception
            MsgBox("LoadSalesPromotionSet:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub BindDataSetA()
        Try
            Dim mTable As New DataTable
            mDatasetA = New DataSet
            With mTable
                .Columns.Add("fSaleOrdeNo")
                .Columns.Add("fWriteNo")
                .Columns.Add("fDeliverMode")
                .Columns.Add("fStoreCode")
                .Columns.Add("fDeliverDate")
                .Columns.Add("fGoodsType")
                .Columns.Add("fCustomerType")
                ''.Columns.Add("listB")
                ''.Columns.Add("CustomerID")
                .Columns.Add("fCustomerName")
                .Columns.Add("fLinkMan")
                .Columns.Add("fLinkPhone")
                .Columns.Add("fAreaID")
                .Columns.Add("fDeliverAddress")
                .Columns.Add("ShopNo")
                .Columns.Add("fEmployeeID")
                .Columns.Add("fSaleDate")
                .Columns.Add("fOrdeStatus")
                .Columns.Add("fOperaterMan")
                .Columns.Add("fOperateDate")
                .Columns.Add("fCheckMan")
                .Columns.Add("fCheckDate")
                .Columns.Add("fPayMode")
                .Columns.Add("fDSIA", GetType(Decimal))
                .Columns.Add("FDSIB", GetType(Decimal))
                .Columns.Add("fBSI", GetType(Decimal))
                .Columns.Add("FTAmount", GetType(Decimal))
                .Columns.Add("FReceipt", GetType(Decimal))
                .Columns.Add("FRefund", GetType(Decimal))
                .Columns.Add("fRemark")
            End With
            mDatasetA.Tables.Add(mTable)
            Me.DGV_Master.DataSource = mDatasetA.Tables(0)
            With Me.DGV_Master
                For i As Integer = 0 To .Columns.Count - 1
                    Dim mKey As String = .Columns(i).Name
                    Dim CaptionStr As String = BindHashTable(0).Item(mKey)
                    If BindHashTable(0).ContainsKey(mKey) = True Then
                        .Columns(i).HeaderText = CaptionStr
                        .Columns(i).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
                        .Columns(i).Visible = True
                    Else
                        .Columns(i).Visible = False
                    End If

                Next
            End With
            With Me.DGV_Master
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                .Columns("fDSIA").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("FDSIB").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("fBSI").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("FTAmount").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("FReceipt").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("FRefund").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .ReadOnly = True
            End With
            With Me.DGV_MasterSum
                .ReadOnly = True
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .ColumnHeadersVisible = False
                .Columns.Add("fSaleOrdeNo", "")
                .Columns.Add("fWriteNo", "")
                .Columns.Add("fDeliverMode", "")
                .Columns.Add("fStoreCode", "")
                .Columns.Add("fDeliverDate", "")
                .Columns.Add("fGoodsType", "")
                .Columns.Add("fCustomerType", "")
                .Columns.Add("fCustomerName", "")
                .Columns.Add("fLinkMan", "")
                ''.Columns.Add("listB", "")
                ''.Columns.Add("CustomerID", "")
                .Columns.Add("fLinkPhone", "")
                .Columns.Add("fAreaID", "")
                .Columns.Add("fDeliverAddress", "")
                .Columns.Add("ShopNo", "")
                .Columns.Add("fEmployeeID", "")
                .Columns.Add("fSaleDate", "")
                .Columns.Add("fOrdeStatus", "")
                .Columns.Add("fOperaterMan", "")
                .Columns.Add("fOperateDate", "")
                .Columns.Add("fCheckMan", "")
                .Columns.Add("fCheckDate", "")
                .Columns.Add("fPayMode", "")
                .Columns.Add("fDSIA", "")
                .Columns.Add("FDSIB", "")
                .Columns.Add("fBSI", "")
                .Columns.Add("FTAmount", "")
                .Columns.Add("FReceipt", "")
                .Columns.Add("FRefund", "")
                .Columns.Add("fRemark", "")
                Dim GridRow As New DataGridViewRow
                .Rows.Add(GridRow)
                .Columns("fDSIA").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("FDSIB").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("fBSI").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("FTAmount").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("FReceipt").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("FRefund").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Rows(0).DefaultCellStyle.BackColor = Color.AliceBlue
                .Rows(0).Cells(0).Value = "合計："
            End With
            SetGridWidth(1)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub BindDataSetB()
        Try
            Dim mTable As New DataTable
            mDatasetB = New DataSet
            With mTable
                .Columns.Add("ItemNo")
                .Columns.Add("fGoodsBarCode")
                .Columns.Add("Code")
                .Columns.Add("Enname")
                .Columns.Add("Cnname")
                .Columns.Add("fGoodsColor")
                .Columns.Add("fGoodsSize")
                .Columns.Add("fSumCount", GetType(Decimal))
                .Columns.Add("SalePrice", GetType(Decimal))
                .Columns.Add("fSumMoney", GetType(Decimal))
                .Columns.Add("fRemark")
            End With
            mDatasetB.Tables.Add(mTable)
            Me.DGV_Detail.DataSource = mDatasetB.Tables(0)

            With Me.DGV_Detail
                For i As Integer = 0 To .Columns.Count - 1
                    Dim mKey As String = .Columns(i).Name
                    Dim CaptionStr As String = BindHashTable(1).Item(mKey)
                    .Columns(i).HeaderText = CaptionStr
                    .Columns(i).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
                Next
                .Columns(0).ReadOnly = True
                .Columns("fSumCount").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("SalePrice").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("fSumMoney").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("fSumCount").DefaultCellStyle.BackColor = Color.AliceBlue
                .Columns("fSumCount").DefaultCellStyle.Format = "#0.00"
                .Columns("SalePrice").ReadOnly = True
                .Columns("fSumMoney").ReadOnly = True
                .Columns("ItemNo").DefaultCellStyle.BackColor = Color.DarkGray
            End With
            With Me.DGV_Sum
                .ReadOnly = True
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                Me.DGV_Sum.Columns.Add("ItemNo", "")
                Me.DGV_Sum.Columns.Add("fGoodsBarCode", "")
                Me.DGV_Sum.Columns.Add("Code", "")
                Me.DGV_Sum.Columns.Add("Enname", "")
                Me.DGV_Sum.Columns.Add("fGoodsName", "")
                Me.DGV_Sum.Columns.Add("fGoodsColor", "")
                Me.DGV_Sum.Columns.Add("fGoodsSize", "")
                Me.DGV_Sum.Columns.Add("fSumCount", "")
                Me.DGV_Sum.Columns.Add("SalePrice", "")
                Me.DGV_Sum.Columns.Add("fSumMoney", "")
                Me.DGV_Sum.Columns.Add("fRemark", "")
                .Columns(0).DefaultCellStyle.BackColor = Color.DarkGray
                .Columns("fSumCount").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("SalePrice").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("fSumMoney").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                Dim GridRow As New DataGridViewRow
                Me.DGV_Sum.Rows.Add(GridRow)
                .Rows(0).Cells(0).Value = "合計："
            End With
            SetGridWidth(0)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub BindDataSetC()

        Try
            Dim mTable As New DataTable
            With mTable
                .Columns.Add("ID")
                .Columns.Add("ListCode")
                .Columns.Add("CardNo")
                .Columns.Add("payMoney_f", GetType(Decimal))
                .Columns.Add("Currency")
                .Columns.Add("Rate", GetType(Decimal))
                .Columns.Add("payMoney_t", GetType(Decimal))
            End With
            mDatasetC = New DataSet
            mDatasetC.Tables.Add(mTable)
            Me.DGV_PayMode.DataSource = mDatasetC.Tables(0)

            With Me.DGV_PayMode
                For i As Integer = 0 To .Columns.Count - 1
                    Dim mKey As String = .Columns(i).Name
                    Dim CaptionStr As String = BindHashTable(2).Item(mKey)
                    .Columns(i).HeaderText = CaptionStr
                    .Columns(i).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
                Next
                .Columns("ID").Visible = False
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .RowHeadersVisible = False
                .Columns("payMoney_f").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("Rate").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("payMoney_t").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("Rate").Width = 60
                .Columns("Currency").Width = 60
                .Columns("payMoney_t").ReadOnly = True
            End With

            Dim sql As String
            sql = "select b.ID,b.ListCode,CardNo='',payMoney_f=0.00,Currency='" & Me.cmbStandardMoney.Text & "',Rate=1.0000,payMoney_t=0.00 from dbo.BSC_OtherDefineA a inner join BSC_OtherDefineB  b on a.ID=b.ItemNo where a.Itemcode='MoneyType'"
            mDatasetC = ReturnDataset(sql)
            Me.DGV_PayMode.DataSource = mDatasetC.Tables(0)

        Catch ex As Exception
            MsgBox("BindDataSetC:" & ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub SetGridWidth(ByVal index As Integer)
        Select Case index
            Case 0
                For i As Integer = 0 To Me.DGV_Detail.Columns.Count - 1
                    Me.DGV_Sum.Columns(i).Width = Me.DGV_Detail.Columns(i).Width
                Next
            Case 1
                For i As Integer = 0 To Me.DGV_Master.Columns.Count - 1
                    Me.DGV_MasterSum.Columns(i).Width = Me.DGV_Master.Columns(i).Width
                Next
        End Select

    End Sub

    Private Function BindHashTable(Optional ByVal Index As Integer = 0) As Hashtable
        Try
            Dim mHash As New Hashtable
            With mHash
                Select Case Index
                    Case 0
                        .Add("fSaleOrdeNo", "合同編號")
                        .Add("fWriteNo", "手寫單號")
                        .Add("fDeliverMode", "送貨類型")
                        .Add("fStoreCode", "到取門市")
                        .Add("fDeliverDate", "送貨日期")
                        .Add("fGoodsType", "單類")
                        .Add("fCustomerType", "客戶類型")
                        ''.Add("listB", "折扣")
                        ''.Add("CustomerID", "客戶編號")
                        .Add("fCustomerName", "客戶名稱")
                        .Add("fLinkMan", "聯系人")
                        .Add("fLinkPhone", "聯系電話")
                        .Add("fAreaID", "區域")
                        .Add("fDeliverAddress", "送貨地址")
                        .Add("ShopNo", "門店")
                        .Add("fEmployeeID", "銷售人員")
                        .Add("fSaleDate", "銷售日期")
                        .Add("fOrdeStatus", "單據狀態")
                        .Add("fOperaterMan", "操作人員")
                        .Add("fOperateDate", "操作日期")
                        .Add("fCheckMan", "審核人員")
                        .Add("fCheckDate", "審核日期")
                        .Add("fPayMode", "付款類型")
                        .Add("fDSIA", "實收訂金")
                        .Add("FDSIB", "應付金額")
                        .Add("fBSI", "尾數")
                        .Add("FTAmount", "總金額")
                        .Add("FReceipt", "付款金額")
                        .Add("FRefund", "找贖")
                        .Add("fRemark", "備注")
                    Case 1
                        .Add("ItemNo", "編號")
                        .Add("fGoodsBarCode", "貨品條碼")
                        .Add("Code", "産品編號")
                        .Add("Enname", "英文編號")
                        .Add("Cnname", "貨品名稱")
                        .Add("fGoodsColor", "顔色")
                        .Add("fGoodsSize", "規格")
                        .Add("fSumCount", "數量")
                        .Add("SalePrice", "單價")
                        .Add("fSumMoney", "總金額")
                        .Add("fRemark", "備注")
                    Case 2
                        .Add("ID", "ID")
                        .Add("ListCode", "方式")
                        .Add("CardNo", "卡號")
                        .Add("payMoney_f", "原幣值")
                        .Add("Currency", "貨幣")
                        .Add("Rate", "漚率")
                        .Add("payMoney_t", "金額")
                End Select
            End With
            Return mHash
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Private Sub ClearText()
        Me.txtWriteNo.Text = ""
        Me.CBStoreCode.Text = ""
        Me.txtArea.Text = ""
        Me.CBCustomerNo.Text = ""
        Me.txtDliveraddress.Text = ""
        Me.txtReciveman.Text = ""
        Me.txtCustomer.Text = ""
        Me.CBCustomerNo.Text = ""
        Me.txtzhekou.Text = ""
        Me.txtCustomePhone.Text = ""
        Me.txtCustomeRemark.Text = ""
        Me.txtSumDSI.Text = "0.00"
        Me.txtSumDSIA.Text = "0.00"
        Me.txtBSI.Text = "0.00"
        Me.txtFTAmount.Text = "0.00"
        Me.CBSelMode.Text = ""
        Me.LabOrdingNo.Text = ""
        Me.NumericUpDown1.Value = 100
        If mDatasetB.Tables(0).Rows.Count > 0 Then
            mDatasetB.Tables(0).Rows.Clear()
            Me.DGV_Detail.DataSource = mDatasetB.Tables(0)
        End If
        Me.CBOrdingMode.SelectedIndex = 0
        Me.CBDeliverMode.SelectedIndex = -1
        Me.CBSaleman.SelectedIndex = -1
        Me.CBSelMode.SelectedIndex = -1
        Me.cmbDept.SelectedIndex = -1
        Me.ComboBox1.SelectedIndex = -1
        Me.txtBalanse.Text = ""
        Me.txtActualAmount.Text = ""
        Me.LabInvNo.Text = ""
        Me.TextBoxShow.Text = ""
        Me.DGV_Sum.Rows(0).Cells("fSumCount").Value = "0.00"
        Me.DGV_Sum.Rows(0).Cells("SalePrice").Value = "0.00"
        Me.DGV_Sum.Rows(0).Cells("fSumMoney").Value = "0.00"
        For i As Integer = 0 To mDatasetC.Tables(0).Rows.Count - 1
            mDatasetC.Tables(0).Rows(i).Item("CardNo") = ""
            mDatasetC.Tables(0).Rows(i).Item("payMoney_f") = "0.00"
            mDatasetC.Tables(0).Rows(i).Item("payMoney_t") = "0.00"
        Next
        Me.DGV_PayMode.DataSource = mDatasetC.Tables(0)
        'mDatasetC.Tables(0).Clear()
        mDatasetC.Tables(0).AcceptChanges()
        DateTimePicker1.Text = ServerDate
        Me.txtOrigint.Text = ""
        Me.txtTranspor.Text = ""
        Me.CBpaymentMethod.Text = ""
        Me.txtPortOfLading.Text = ""
        Me.txtportOfDestination.Text = ""
        Me.txtPacking.Text = ""
        Me.txtBuys.Text = ""
        Me.txtSallers.Text = ""
        Me.txtInsurance.Text = ""
        Me.txtClaims.Text = ""
        Me.txtArbitration.Text = ""
        Me.txtForccMajeure.Text = ""
        Me.TxtPath.Text = ""
        Me.txtShippingMarks.Text = ""
        Me.txtQtyPriceAmount.Text = ""
        Me.txtSelModeOther.Text = ""
        Me.TxtOther.Text = ""
        Me.CBSelMode.SelectedIndex = -1
    End Sub

    ''' <summary>
    ''' 設置按鈕的 Enabled 屬性
    ''' </summary>
    ''' <param name="B"></param>
    ''' <remarks></remarks>
    Private Sub SetEnable(ByVal B As Boolean)
        Me.txtWriteNo.Enabled = B
        Me.CBSaleman.Enabled = B
        Me.CBStoreCode.Enabled = B
        '在這裡爲什麽要設置為False，會影響其他的操作嗎
        Me.txtSaleDate.Enabled = False
        Me.CBCustomerNo.Enabled = B
        Me.cbmCustomeType.Enabled = B
        Me.txtDliveraddress.Enabled = B
        Me.ComboBox1.Enabled = B
        Me.CBDeliverMode.Enabled = B
        Me.DateTimePicker1.Enabled = B
        Me.txtReciveman.Enabled = B
        Me.txtCustomer.Enabled = B
        Me.txtCustomePhone.Enabled = B
        Me.txtArea.Enabled = B
        Me.txtCustomeRemark.ReadOnly = Not B
        Me.txtSumDSI.Enabled = False
        Me.txtBSI.Enabled = False
        Me.CBSelMode.Enabled = B
        Me.DGV_Detail.AllowUserToAddRows = B
        Me.DGV_Detail.AllowUserToDeleteRows = B
        Me.txtBalanse.Enabled = False
        Me.DGV_Detail.ReadOnly = Not B
        Me.NumericUpDown2.Enabled = False
        Me.txtSumDSIA.Enabled = False
        Me.NumericUpDown1.Enabled = False
        Me.txtActualAmount.Enabled = B
        Me.cmbDept.Enabled = B
        Me.BtnArea.Enabled = B
        Me.cmbDept.Enabled = B
        'Me.Panel3.Enabled = B
        Me.GroupBox5.Enabled = B
        Me.txtQtyPriceAmount.Enabled = B
        Me.CBpaymentMethod.Enabled = B
        Me.txtSelModeOther.Enabled = B
        Me.txtPacking.Enabled = B
        Me.txtShippingMarks.Text = B
        Me.txtInsurance.Enabled = B
        Me.txtClaims.Enabled = B
        Me.txtArbitration.Enabled = B
        Me.txtShippingMarks.Enabled = B
        Me.txtForccMajeure.Enabled = B
        Me.TxtOther.Enabled = B
        Me.cmbStandardMoney.Enabled = B
        Me.DGV_Detail.Columns("ItemNo").ReadOnly = True
        Me.DGV_Detail.Columns("SalePrice").ReadOnly = True
        Me.DGV_Detail.Columns("fSumMoney").ReadOnly = True
    End Sub

    Private Sub LoadBasicData()
        Try
            Dim sql As String = ""
            sql = "select fCode,fCName from BSC_Employee ;"
            If fDefine = 0 Then
                sql += "select fCode,fName from dbo.BSC_StoreHouse ;"
            Else
                sql += "select fCode,fName from BSC_StoreHouse where fCode='" & PubCompanyCode & "';"
            End If
            sql += "select a.*,b.* from dbo.BSC_OtherDefineA a inner join BSC_OtherDefineB b  on a.ID=b.ItemNo where a.ItemCode='SaleType' ;"
            sql += "select b.* from BSC_OtherDefineA a inner join BSC_OtherDefineB b on a.Id=b.ItemNo where a.ItemCode='BillstatusDefine';"
            sql += "select b.* from BSC_OtherDefineA a inner join BSC_OtherDefineB b on a.ID=b.ItemNo where a.ItemCode='CustomerType' and listcode='Retail';"
            sql += "select b.* from dbo.BSC_OtherDefineA a inner join BSC_OtherDefineB  b on a.ID=b.ItemNo inner join BSC_SystemProfile c on b.ListCode=c.FValue "
            sql += "where a.ItemCode='CurrencyDefine' and Fkey='Standard money';"
            sql += "select b.* from dbo.BSC_OtherDefineA a inner join BSC_OtherDefineB  b on a.ID=b.ItemNo where a.Itemcode='Payterm';"
            sql += "select b.* from dbo.BSC_OtherDefineA a inner join BSC_OtherDefineB b on a.Id=b.ItemNo  where a.ItemCode='InvoiceType';"
            sql += "select fCode,fName from dbo.BSC_StoreHouse ;"
            sql += "select ID,fCode,fCName from dbo.BSC_GoodsType where fParentID=0"

            M_Ds = New DataSet
            M_Ds = ReturnDataset(sql)

            Me.CBSaleman.Items.Clear()
            Me.CBSaleman.DisplayMember = "fCName"
            Me.CBSaleman.ValueMember = "fCode"
            Me.CBSaleman.DataSource = M_Ds.Tables(0)

            Me.CBStoreCode.Items.Clear()
            Me.CBStoreCode.DataSource = M_Ds.Tables(1)
            Me.CBStoreCode.DisplayMember = "fName"
            Me.CBStoreCode.ValueMember = "fCode"
            If Me.CBStoreCode.Items.Count > 0 Then
                Me.CBStoreCode.SelectedIndex = 0
            End If


            Me.CBDeliverMode.Items.Clear()
            Me.CBDeliverMode.DisplayMember = "ListA"
            Me.CBDeliverMode.ValueMember = "ListCode"
            Me.CBDeliverMode.DataSource = M_Ds.Tables(2)

            Me.CBOrdingMode.Items.Clear()
            Me.CBOrdingMode.DisplayMember = "ListA"
            Me.CBOrdingMode.ValueMember = "ListCode"
            Me.CBOrdingMode.DataSource = M_Ds.Tables(3)
            Me.CBOrdingMode.SelectedIndex = 0
            Me.CBOrdingMode.Enabled = False

            Dim mTable As DataTable = CType(Me.CBOrdingMode.DataSource, DataTable)
            Me.OrdeMode.DisplayMember = "ListA"
            Me.OrdeMode.ValueMember = "ListCode"
            Me.OrdeMode.DataSource = mTable
            Me.OrdeMode.SelectedIndex = -1

            Dim nTable As DataTable = CType(Me.CBSaleman.DataSource, DataTable)
            Me.SaleMan.DisplayMember = "fCName"
            Me.SaleMan.ValueMember = "fCode"
            Me.SaleMan.DataSource = nTable
            Me.SaleMan.SelectedIndex = -1

            Me.cbmCustomeType.Items.Clear()
            Me.cbmCustomeType.DisplayMember = "ListA"
            Me.cbmCustomeType.ValueMember = "Listcode"
            Me.cbmCustomeType.DataSource = M_Ds.Tables(4)

            Me.OrderCustomerType.Items.Clear()
            Me.OrderCustomerType.DisplayMember = "ListA"
            Me.OrderCustomerType.ValueMember = "Listcode"
            Me.OrderCustomerType.DataSource = M_Ds.Tables(4)

            Me.cmbStandardMoney.DisplayMember = "ListA"
            Me.cmbStandardMoney.ValueMember = "Listcode"
            Me.cmbStandardMoney.DataSource = M_Ds.Tables(5)
            Me.cmbStandardMoney.SelectedIndex = 0
            '  Me.cmbStandardMoney.Enabled = True

            Me.CBSelMode.DisplayMember = "ListA"
            Me.CBSelMode.ValueMember = "Listcode"
            Me.CBSelMode.DataSource = M_Ds.Tables(6)
            Me.CBSelMode.SelectedIndex = -1

            Me.cmbInvType.DisplayMember = "ListA"
            Me.cmbInvType.ValueMember = "Listcode"
            Me.cmbInvType.DataSource = M_Ds.Tables(7)
            Me.cmbInvType.SelectedValue = "DEPOSIT"
            Me.cmbInvType.Enabled = False

            Me.ComboBox1.DisplayMember = "fName"
            Me.ComboBox1.ValueMember = "fCode"
            Me.ComboBox1.DataSource = M_Ds.Tables(8)
            Me.ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList
            Me.ComboBox1.SelectedIndex = -1

            Me.cmbDept.DisplayMember = "fCName"
            Me.cmbDept.ValueMember = "fCode"
            Me.cmbDept.DataSource = M_Ds.Tables(9)
            Me.cmbDept.DropDownStyle = ComboBoxStyle.DropDownList
            Me.cmbDept.SelectedIndex = -1

            Dim aTable As DataTable = CType(Me.cmbDept.DataSource, DataTable)
            LoadOrdeType(aTable)

            Dim bTable As DataTable = CType(Me.ComboBox1.DataSource, DataTable)
            Me.OrdeShopNo.DisplayMember = "fName"
            Me.OrdeShopNo.ValueMember = "fCode"
            Me.OrdeShopNo.DataSource = bTable
            Me.OrdeShopNo.SelectedIndex = -1


            Dim cTable As DataTable = CType(Me.CBDeliverMode.DataSource, DataTable)
            Me.DeliverType.ValueMember = "ListCode"
            Me.DeliverType.DisplayMember = "ListA"
            Me.DeliverType.DataSource = cTable
            Me.DeliverType.SelectedIndex = -1


            aTable = Nothing
            bTable = Nothing
            cTable = Nothing
        Catch ex As Exception
            MsgBox("LoadBasicData:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub LoadOrdeType(ByVal dt As DataTable)

        Try
            Dim Nodes As New TreeNode
            Nodes.Nodes.Clear()
            Nodes.Text = "全部"
            Nodes.Tag = "All"
            Me.TreeView1.Nodes.Add(Nodes)

            Dim mNode As TreeNode
            For Each mRow As DataRow In dt.Rows
                mNode = New TreeNode

                mNode.Tag = mRow("fCode") & ""
                mNode.Text = mRow("fCName") & ""
                Nodes.Nodes.Add(mNode)
            Next
            Me.Panel5.Left = Me.txtOrdeType.Left
            Me.Panel5.Top = 0
            Me.Panel5.Width = Me.txtOrdeType.Width
            Me.TreeView1.ExpandAll()
        Catch ex As Exception
            MsgBox("LoadOrdeType:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub LoadGoods()
        Try
            Dim sql As String = ""
            sql = "select replace(a.BarCode,'*','') as fGoodsBarCode,a.Code,a.Enname,a.Cnname,b.ColorSName as fGoodsColor,c.SizeSname as fGoodsSize,a.SalePrice,a.Dept from BSC_Goods a inner join BSC_ColorDefine b on a.Color=b.ColorCode inner join BSC_SizeDefine c on a.Spec=c.SizeCode;"
            sql += "select b.* from dbo.BSC_OtherDefineA a inner join BSC_OtherDefineB b on a.ID=b.ItemNo where a.ItemCode='EarnestSet'"

            dsGoods = New DataSet
            dsGoods = ReturnDataset(sql)
            Me.NumericUpDown2.Value = Convert.ToDecimal(dsGoods.Tables(1).Rows(0).Item("ListCode") & "")
        Catch ex As Exception
            MsgBox("LoadGoods:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub LoadCurrency()

        Try
            Dim sql As String
            Dim m_Ds As New DataSet
            '' Dim Item As ListViewItem
            sql = "select b.* from dbo.BSC_OtherDefineA a inner join BSC_OtherDefineB  b on a.ID=b.ItemNo"
            sql += " where a.ItemCode='CurrencyDefine'"
            m_Ds = ReturnDataset(sql)

            If m_Ds.Tables(0).Rows.Count > 0 Then
                ComBox.DisplayMember = "ListA"
                ComBox.ValueMember = "ListCode"
                ComBox.DataSource = m_Ds.Tables(0)
                ComBox.DropDownStyle = ComboBoxStyle.DropDownList
                ComBox.SelectedIndex = ComBox.FindString(Me.cmbStandardMoney.Text)
            End If
        Catch ex As Exception
            MsgBox("LoadCurrency:" & ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub FillText(ByVal SaleOrdeNo As String)
        Try
            ClearText()
            Me.LabInvNo.Text = ""
            Dim Rows() As DataRow = mDatasetA.Tables(0).Select("fSaleOrdeNo='" & SaleOrdeNo & "'")
            Dim sql As String = ""
            Dim sqlstr As String = ""
            Dim m_Ds As New DataSet
            If Rows.Length > 0 Then
                sqlstr = "select * from Sal_InvoiceA where FSaleOrdeNo='" & SaleOrdeNo & "';"
                sqlstr += "select m.*,n.*,h.ListA as Moneytype from Sal_InvoiceA g inner join dbo.Sal_InvoiceC m on g.FNum=m.FNum left join "
                sqlstr += "(select b.Id,b.ItemNo,b.ListCode,b.ListA from dbo.BSC_OtherDefineA a inner join dbo.BSC_OtherDefineB b on a.Id=b.ItemNo where ItemCode='MoneyType') n on m.PayMoneytype=n.Id left join"
                sqlstr += " (select b.Id,b.ItemNo,b.ListCode,b.ListA from dbo.BSC_OtherDefineA a inner join dbo.BSC_OtherDefineB b on a.Id=b.ItemNo where ItemCode='CurrencyDefine') h on m.FCurrency=h.ListCode"
                sqlstr += " where g.FSaleOrdeNo='" & SaleOrdeNo & "'"
                m_Ds = ReturnDataset(sqlstr)
                If m_Ds.Tables(0).Rows.Count > 0 Then
                    Me.LabInvNo.Text = m_Ds.Tables(0).Rows(0)("FNum")
                    Me.cmbInvType.SelectedValue = m_Ds.Tables(0).Rows(0)("Ftype")
                    Dim PayMoneyType As String = ""
                    ''Dim Rowindex As Integer

                    For Each mRow As DataRow In m_Ds.Tables(1).Rows
                        PayMoneyType = mRow("ListCode") & ""
                        For i As Integer = 0 To Me.DGV_PayMode.Rows.Count - 1
                            If Me.DGV_PayMode.Rows(i).Cells("ListCode").Value.ToString.ToLower = PayMoneyType.ToLower Then
                                Me.DGV_PayMode.Rows(i).Cells("CardNo").Value = mRow("PayMoneyCardNo") & ""
                                Me.DGV_PayMode.Rows(i).Cells("payMoney_f").Value = mRow("PayMoney") & ""
                                Me.DGV_PayMode.Rows(i).Cells("Currency").Value = mRow("Moneytype") & ""
                                Me.DGV_PayMode.Rows(i).Cells("Rate").Value = mRow("FRate") & ""
                                Me.DGV_PayMode.Rows(i).Cells("payMoney_t").Value = mRow("PayMoney_Loc") & ""
                            End If
                        Next
                    Next
                End If
                For Each mRow As DataRow In Rows
                    Me.LabOrdingNo.Text = mRow("fSaleOrdeNo") & ""
                    Me.txtWriteNo.Text = mRow("fWriteNo") & ""
                    Me.CBSaleman.Text = mRow("fEmployeeID") & ""
                    Me.cmbDept.Text = mRow("fGoodsType") & ""
                    Me.CBOrdingMode.Text = mRow("fOrdeStatus") & ""
                    Me.txtArea.Text = mRow("fAreaID") & ""
                    Me.CBStoreCode.Text = mRow("ShopNo") & ""
                    Me.txtSaleDate.Value = CDate(mRow("fSaleDate") & "")
                    Me.txtCustomer.Text = mRow("fCustomerName") & ""
                    If mRow("fcustomerType") & "" = "" Then
                        Me.cbmCustomeType.Text = ""
                    Else
                        Me.cbmCustomeType.Text = mRow("fcustomerType") & ""
                    End If

                    Me.txtDliveraddress.Text = mRow("fDeliverAddress") & ""
                    If mRow("fDeliverDate") & "" = "" Then
                    Else
                        Me.DateTimePicker1.Value = mRow("fDeliverDate") & ""
                    End If
                    Me.CBDeliverMode.Text = mRow("fDeliverMode") & ""
                    Dim a As String
                    a = mRow("fStoreCode") & ""
                    Me.ComboBox1.Text = a
                    Me.ComboBox1.Enabled = False
                    Me.txtReciveman.Text = mRow("fLinkMan") & ""
                    Me.txtCustomePhone.Text = mRow("fLinkPhone") & ""
                    Me.txtCustomeRemark.Text = mRow("fRemark") & ""
                    Me.LabAreaID.Text = Me.txtArea.Text.Split("\")(Me.txtArea.Text.Split("\").Length - 1)

                    Me.txtSumDSIA.Text = mRow("fDSIB") & ""
                    Me.txtBSI.Text = mRow("fBSI") & ""
                    Me.txtSumDSI.Text = mRow("FReceipt") & ""
                    Me.txtBalanse.Text = mRow("FRefund") & ""
                    Me.txtFTAmount.Text = mRow("FTAmount") & ""
                    Me.txtActualAmount.Text = mRow("FDSIA") & ""
                    Me.CBSelMode.Text = mRow("fPayMode") & ""
                    If mRow("fDeliverDate") = "" Then
                    Else
                        Me.DateTimePicker1.Value = mRow("fDeliverDate") & ""
                    End If

                    If mRow("fCustomerName") & "" = "" Then
                    Else
                        Me.CBCustomerNo.Text = mRow("fCustomerName")
                    End If

                    ''Me.txtzhekou.Text = mRow("listB")
                Next
            End If

            sql = "select distinct a.ItemNo,replace(a.fGoodsBarcode,'*','') as fGoodsBarCode,b.Code,b.Enname,b.Cnname,c.ColorSName as fGoodsColor,d.SizeSname as fGoodsSize,a.fSumCount,SalePrice=cast((a.fSumMoney/(case fSumCount when 0.00 then 1 else fSumCount end)) as money),a.fSumMoney,a.fRemark "
            sql += "from Sal_SaleOrdeB a left join BSC_Goods b on a.fGoodsBarCode=b.Barcode left join "
            sql += "BSC_ColorDefine c on b.Color=c.ColorCode left join BSC_SizeDefine d on b.Spec=d.SizeCode where fSaleOrdeNo='" & SaleOrdeNo & "';"
            sql += "     select  Top(1) fSaleOrdeNo, Origin, TransportMode, paymentMethod, PortOfLoading, PortOfDestination, Packing, Buyer, Saller, Insurance, claims, Arbitration, ForceMajeure, SourceDocPath,ShippingMarks,QtyPriceAmount,SelModeOther,Other from Sal_SaleOrdeD "
            sql += "  where fSaleOrdeNo='" & SaleOrdeNo & "'"


            mDatasetB = ReturnDataset(sql)
            If Me.cbmCustomeType.SelectedValue <> "Retail" Then
                Me.txtOrigint.Text = mDatasetB.Tables(1).Rows(0)("Origin")
                Me.txtTranspor.Text = mDatasetB.Tables(1).Rows(0)("TransportMode")
                Me.CBpaymentMethod.Text = mDatasetB.Tables(1).Rows(0)("paymentMethod")
                Me.txtPortOfLading.Text = mDatasetB.Tables(1).Rows(0)("PortOfLoading")
                Me.txtportOfDestination.Text = mDatasetB.Tables(1).Rows(0)("PortOfDestination")
                Me.txtPacking.Text = mDatasetB.Tables(1).Rows(0)("Packing")
                Me.txtBuys.Text = mDatasetB.Tables(1).Rows(0)("Buyer")
                Me.txtSallers.Text = mDatasetB.Tables(1).Rows(0)("Saller")
                Me.txtInsurance.Text = mDatasetB.Tables(1).Rows(0)("Insurance")
                Me.txtClaims.Text = mDatasetB.Tables(1).Rows(0)("claims")
                Me.txtArbitration.Text = mDatasetB.Tables(1).Rows(0)("Arbitration")
                Me.txtForccMajeure.Text = mDatasetB.Tables(1).Rows(0)("ForceMajeure")
                Me.TxtPath.Text = mDatasetB.Tables(1).Rows(0)("SourceDocPath")
                Me.txtShippingMarks.Text = mDatasetB.Tables(1).Rows(0)("ShippingMarks") & ""
                Me.txtQtyPriceAmount.Text = mDatasetB.Tables(1).Rows(0)("QtyPriceAmount") & ""
                Me.txtSelModeOther.Text = mDatasetB.Tables(1).Rows(0)("SelModeOther") & ""
                Me.TxtOther.Text = mDatasetB.Tables(1).Rows(0)("Other") & ""
            End If
            Me.DGV_Detail.DataSource = mDatasetB.Tables(0)
            If mDatasetB.Tables(0).Rows.Count > 0 Then
                Me.DGV_Sum.Rows(0).Cells("fSumCount").Value = Format(mDatasetB.Tables(0).Compute("sum(fSumCount)", ""), "#0.00")
                Me.DGV_Sum.Rows(0).Cells("fSumMoney").Value = Format(mDatasetB.Tables(0).Compute("sum(fSumMoney)", ""), "#0.00")
            End If
        Catch ex As Exception
            ''MsgBox("FillText:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Function JudgeExistRecorder(ByVal CustomerID As String) As Boolean

        Dim sql As String
        Dim m_Ds As New DataSet
        Try
            sql = "select * from where ID=" & CustomerID
            m_Ds = ReturnDataset(sql)
            If m_Ds.Tables(0).Rows.Count > 0 Then
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            MsgBox("JudgeExistRecorder:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    Private Function ReturnTable(ByVal SaleOrdeNo As String) As DataTable
        Try
            Dim mTable As New DataTable
            With mTable
                .Columns.Add("fSaleOrdeNo")
                .Columns.Add("ItemNo")
                .Columns.Add("fGoodsBarCode")
                .Columns.Add("fSumCount")
                .Columns.Add("fSumMoney")
                .Columns.Add("fRemark")
            End With
            For Each Row As DataRow In mDatasetB.Tables(0).Rows
                Dim mRow As DataRow = mTable.NewRow
                mRow("fSaleOrdeNo") = SaleOrdeNo
                mRow("ItemNo") = Row("ItemNo") & ""
                mRow("fGoodsBarCode") = "*" & Row("fGoodsBarCode") & "*"
                mRow("fSumCount") = Row("fSumCount") & ""
                mRow("fSumMoney") = Row("fSumMoney") & ""
                mRow("fRemark") = Row("fRemark") & ""
                mTable.Rows.Add(mRow)
            Next
            mTable.AcceptChanges()
            Return mTable
        Catch ex As Exception
            MsgBox("ReturnTable:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
            Return Nothing
        End Try
    End Function

    Private Function ReturnTable1(ByVal SaleOrdeNo As String) As DataTable

        Try
            Dim mTable As New DataTable
            With mTable
                .Columns.Add("fSaleOrdeNo")
                .Columns.Add("PayMoneyType")
                .Columns.Add("PayMoneyCardNo")
                .Columns.Add("PayMoney")
                .Columns.Add("FCurrency")
                .Columns.Add("FRate")
                .Columns.Add("PayMoney_Loc")
            End With

            For Each mRow As DataRow In mDatasetC.Tables(0).Rows
                Dim Row As DataRow = mTable.NewRow
                If mRow("payMoney_t") = "0.00" Or mRow("payMoney_t") & "" = "" Then
                Else
                    Row("fSaleOrdeNo") = SaleOrdeNo
                    Row("PayMoneyType") = mRow("ID")
                    Row("PayMoneyCardNo") = mRow("CardNo")
                    Row("PayMoney") = mRow("payMoney_f")
                    Row("FCurrency") = mRow("Currency")
                    Row("FRate") = mRow("Rate")
                    Row("PayMoney_Loc") = mRow("payMoney_t")
                End If
            Next
            Return mTable
        Catch ex As Exception
            MsgBox("ReturnTable1:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
            Return Nothing
        End Try

    End Function

    Private Function ReturnSqlStr(ByVal InvNo As String) As String

        Dim sqlstr As String = ""
        Dim PayMoneyType As String = ""
        Dim PayMoneyCardNo As String = ""
        Dim PayMoney As Double = 0
        Dim FCurrency As String = ""
        Dim FRate As Double = 0
        Dim PayMoney_Loc As Double = 0

        Try
            For i As Integer = 0 To Me.DGV_PayMode.Rows.Count - 1
                If Me.DGV_PayMode.Rows(i).Cells("payMoney_t").Value Is DBNull.Value Or Me.DGV_PayMode.Rows(i).Cells("payMoney_t").Value = "0.00" Then
                Else
                    PayMoneyType = Me.DGV_PayMode.Rows(i).Cells("ID").Value
                    PayMoneyCardNo = Me.DGV_PayMode.Rows(i).Cells("CardNo").Value
                    PayMoney = Convert.ToDouble(Me.DGV_PayMode.Rows(i).Cells("payMoney_f").Value)
                    FRate = Convert.ToDouble(Me.DGV_PayMode.Rows(i).Cells("Rate").Value)
                    PayMoney_Loc = Convert.ToDouble(Me.DGV_PayMode.Rows(i).Cells("payMoney_t").Value)
                    If Me.DGV_PayMode.Rows(i).Cells("Currency").Value.ToString.ToLower = Me.cmbStandardMoney.Text.ToLower Then
                        FCurrency = Me.cmbStandardMoney.SelectedValue.ToString
                    Else
                        FCurrency = Me.DGV_PayMode.Rows(i).Cells("Currency").Tag
                    End If
                    If Me.DGV_PayMode.Rows(i).Cells(1).Value.ToString().Equals("Gift", StringComparison.InvariantCultureIgnoreCase) Then
                        sqlstr += "update BSC_Gift set status=1 where num='" + PayMoneyCardNo + "'" + vbNewLine
                    Else
                        sqlstr += "Insert Into Sal_InvoiceC(FNum,PayMoneyType,PayMoneyCardNo,PayMoney,FCurrency,FRate,PayMoney_Loc) values('" & InvNo & "','" & PayMoneyType & "','" & PayMoneyCardNo & "'," & PayMoney & ",'" & FCurrency & "'," & FRate & "," & PayMoney_Loc & ");" + vbNewLine
                    End If

                End If
            Next
            Return sqlstr

        Catch ex As Exception
            MsgBox("ReturnSqlStr:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function


    Private Function BtnActionSave() As Boolean

        If ActionInitialize() = False Then Exit Function

        Dim sqlConn As New SqlConnection
        Dim SqlCmd As New SqlClient.SqlCommand
        Dim SqlBulk As SqlClient.SqlBulkCopy
        Dim m_Ds As New DataSet
        Dim sql As String = ""
        Dim SqlStr As String = ""
        Dim SaleOrdeNo As String = ""
        Dim InvNo As String = ""
        Dim WriteNo As String = Me.txtWriteNo.Text.Trim
        Dim DeliverMode As String = Me.CBDeliverMode.SelectedValue
        Dim fGoodsType As String = Me.cmbDept.SelectedValue.ToString
        Dim fDeliverDate As String = Format(Me.DateTimePicker1.Value, "yyyy-MM-dd")
        Dim fCustomerType As String = Me.cbmCustomeType.SelectedValue.ToString
        Dim CustomerID As String = ""
        Dim fCustomerName As String = Me.txtCustomer.Text
        Dim fLinkMan As String = Me.txtReciveman.Text
        Dim fLinkPhone As String = Me.txtCustomePhone.Text
        Dim fDeliverAddress As String = Me.txtDliveraddress.Text
        Dim SaleMan As String = Me.CBSaleman.SelectedValue
        Dim SaleDate As String = Format(Me.txtSaleDate.Value, "yyyy-MM-dd")
        Dim OperateMan As String = PubUserName
        Dim OperateDate As String = ServerDate
        Dim Storecode As String = ""
        Dim OrdeStatus As String = Me.CBOrdingMode.SelectedValue
        Dim Remark As String = Me.txtCustomeRemark.Text.Trim.Replace(",", "").Replace("'", "")
        Dim DSIA As String = IIf(isNull(Me.txtActualAmount.Text), "0", Me.txtActualAmount.Text)
        Dim DSIB As String = IIf(isNull(Me.txtSumDSIA.Text), "0", Me.txtSumDSIA.Text)
        Dim BSI As String = IIf(isNull(Me.txtBSI.Text), "0", Me.txtBSI.Text)
        Dim FTAmount As String = Me.txtFTAmount.Text
        Dim FReceipt As String = Me.txtSumDSI.Text
        Dim FRefund As String = IIf(isNull(Me.txtBalanse.Text), "0", Me.txtBalanse.Text)
        Dim PayMode As String = Me.CBSelMode.Text
        Dim CustomerType As String = Me.cbmCustomeType.SelectedValue.ToString


        'Sal_SaleOrdeD中的數據
        Dim Origin As String = Me.txtOrigint.Text '產地
        Dim paymentMethod As String = Me.CBpaymentMethod.Text  '付款方式
        Dim TransportMode As String = Me.txtTranspor.Text '運輸方式
        Dim PortOfLoading As String = Me.txtPortOfLading.Text '起始港口
        Dim PortOfDestination As String = Me.txtportOfDestination.Text '目的港口
        Dim Packing As String = Me.txtPacking.Text '包裝
        Dim Buyer As String = Me.txtBuys.Text '簽約地點
        Dim Saller As String = Me.txtSallers.Text '裝運期
        Dim Insurance As String = Me.txtInsurance.Text '保險
        Dim claims As String = Me.txtClaims.Text '索賠
        Dim Arbitration As String = Me.txtArbitration.Text '仲裁
        Dim ForceMajeure As String = Me.txtForccMajeure.Text '不可抗力
        Dim SourceDocPath As String = Me.TxtPath.Text '原始文件路徑
        Dim ShippingMarks As String = Me.txtShippingMarks.Text '裝運標記
        Dim QtyPriceAmount As String = Me.txtQtyPriceAmount.Text '數量\單價\總額
        Dim SelModeOther As String = Me.txtSelModeOther.Text '付款條款詳情
        Dim Other As String = Me.TxtOther.Text '其他條款




        sqlConn = GetConn()
        If sqlConn.State = ConnectionState.Closed Then
            sqlConn.Open()
        End If
        Dim SqlTran As SqlClient.SqlTransaction = sqlConn.BeginTransaction

        Try
            If Me.CBCustomerNo.SelectedValue Is Nothing Then
                CustomerID = Me.CBCustomerNo.Text
            Else
                CustomerID = Me.CBCustomerNo.SelectedValue.ToString
            End If
            If Me.CBDeliverMode.SelectedIndex = 0 Then
                Storecode = Me.ComboBox1.SelectedValue
            Else
                Storecode = ""
            End If
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
                SaleOrdeNo = AutoGetNo(PubCompanyCode, "fSaleOrdeNo", "Sal_SaleOrdeA", 1)
                ''If Me.CBCustomerNo.SelectedValue Is Nothing Then
                sql = " Insert Into Sal_SaleOrdeA(fSaleOrdeNo,fWriteNo,fDeliverMode,fDeliverDate,fGoodsType,fCustomerType,fCustomerID,fCustomerName,fLinkMan,fLinkPhone,fDeliverAddress,fAreaID,ShopNo,fEmployeeID,fSaleDate,fOperaterMan,fOperateDate,fOrdeStatus,fStoreCode,fDSIA,fDSIB,fBSI,FTAmount,FRefund,fPayMode,fRemark,fBuiltComputer) values('"
                sql += SaleOrdeNo & "','" & WriteNo & "','" & DeliverMode & "','" & fDeliverDate & "','" & fGoodsType & "','" & fCustomerType & "','" & CustomerID & "','" & fCustomerName & "','" & fLinkMan & "','" & fLinkPhone & "','" & fDeliverAddress & "','" & Me.LabAreaID.Text & "','" & PubCompanyCode & "','" & SaleMan & "','" & SaleDate & "','" & OperateMan & "','"
                sql += OperateDate & "','" & OrdeStatus & "','" & Storecode & "','" & DSIA & "','" & DSIB & "','" & BSI & "','" & FTAmount & "','" & FRefund & "','" & PayMode & "','" & Remark & "','" & My.Computer.Name & "')"
                If CustomerType <> "Retail" Then
                    sql += " Insert Into Sal_SaleOrdeD(fSaleOrdeNo, Origin, TransportMode, paymentMethod, PortOfLoading, PortOfDestination, Packing, Buyer, Saller, Insurance, claims, Arbitration, ForceMajeure, SourceDocPath,ShippingMarks,QtyPriceAmount,SelModeOther,Other) "
                    sql += " VALUES ('" & SaleOrdeNo & "','" & Origin & "','" & TransportMode & "','" & paymentMethod & "','" & PortOfLoading & "','" & PortOfDestination & "','" & Packing & "','" & Buyer & "','" & Saller & "','" & Insurance & "','" & claims & "','" & Arbitration & "','" & ForceMajeure & "','" & SourceDocPath & "','" & ShippingMarks & "','" & QtyPriceAmount & "','" & SelModeOther & "','" & Other & "')"
                End If
                ''Else
                ''    sql = " Insert Into Sal_SaleOrdeA(fSaleOrdeNo,fWriteNo,fDeliverMode,fDeliverDate,fGoodsType,fCustomerType,fCustomerID,fAreaID,ShopNo,fEmployeeID,fSaleDate,fOperaterMan,fOperateDate,fOrdeStatus,fStoreCode,fDSIA,fDSIB,fBSI,FTAmount,FRefund,fPayMode,fRemark,fBuiltComputer) values('"
                ''    sql += SaleOrdeNo & "','" & WriteNo & "','" & DeliverMode & "','" & fDeliverDate & "','" & fGoodsType & "','" & fCustomerType & "','" & CustomerID & "','" & Me.LabAreaID.Text & "','" & PubCompanyCode & "','" & SaleMan & "','" & SaleDate & "','" & OperateMan & "','"
                ''    sql += OperateDate & "','" & OrdeStatus & "','" & Storecode & "'," & DSIA & "," & DSIB & "," & BSI & "," & FTAmount & "," & FRefund & ",'" & PayMode & "','" & Remark & "','" & My.Computer.Name & "')"
                ''End If

                With SqlCmd
                    .Connection = sqlConn
                    .Transaction = SqlTran
                    .CommandType = CommandType.Text
                    .CommandText = sql
                    .ExecuteNonQuery()
                End With

                Dim mTable As DataTable = ReturnTable(SaleOrdeNo)
                SqlBulk = New SqlClient.SqlBulkCopy(sqlConn, SqlBulkCopyOptions.Default, SqlTran)
                SqlBulk.DestinationTableName = "dbo.Sal_SaleOrdeB"
                SqlBulk.BulkCopyTimeout = 100
                SqlBulk.WriteToServer(mTable)


                If Me.cbmCustomeType.SelectedValue = "Retail" Then



                    InvNo = AutoGetNo(PubCompanyCode, "FNum", "Sal_InvoiceA", 2)
                    Dim InvDate As String = ServerDate
                    Dim InvType As String = Me.cmbInvType.SelectedValue.ToString
                    SqlStr += "Insert Into Sal_InvoiceA(FNum,fDate,ShopNo,FSaleOrdeNo,FType,FDSIA,FDSIB,FBSI,FTAmount,FReceipt,FRefund,BulidDate,BulidBy,BulidComputer) values('" & InvNo & "','" & ServerDate
                    SqlStr += "','" & PubCompanyCode & "','" & SaleOrdeNo & "','" & InvType & "','" & Me.txtActualAmount.Text & "','" & Me.txtSumDSIA.Text & "','" & Me.txtBSI.Text & "','" & Me.txtFTAmount.Text & "','" & Me.txtSumDSI.Text & "','" & Me.txtBalanse.Text & "','"
                    SqlStr += ServerDate & "','" & PubUserName & "','" & My.Computer.Name & "');"
                    SqlStr += ReturnSqlStr(InvNo)
                    With SqlCmd
                        .Connection = sqlConn
                        .Transaction = SqlTran
                        .CommandType = CommandType.Text
                        .CommandText = SqlStr
                        .ExecuteNonQuery()
                    End With

                    If Me.CBDeliverMode.SelectedIndex = 2 Then
                        Dim InvNum As String = ""
                        SqlStr = ""
                        InvNum = GetValue("select dbo.GetMaxNum('SalInvoice')")
                        SqlStr += "Insert Into Sal_InvoiceA(FNum,FDate,ShopNo,FSaleOrdeNo,FWriteNo,FType,FNeedDate,FRdeliver,FDSIA,FDSIB,FBSI,FTAmount,BillstatusID,BulidDate,BulidComputer,BulidBy) values('"
                        SqlStr += InvNum & "','" & OperateDate & "','" & PubCompanyCode & "','" & SaleOrdeNo & "','" & WriteNo & "','BALANCE','" & OperateDate & "',1,0.00,'" & Me.txtBSI.Text & " ',0.00,'" & txtBSI.Text & " ','A','" & ServerDate & "','" & My.Computer.Name & "','" & PubUserName & "')"
                        SqlStr += "update Number set Number=Number+1 where BillType='SalInvoice'"
                        With SqlCmd
                            .Connection = sqlConn
                            .Transaction = SqlTran
                            .CommandType = CommandType.Text
                            .CommandText = SqlStr
                            .ExecuteNonQuery()
                        End With
                    End If
                    Me.LabInvNo.Text = InvNo
                End If
                Me.LabOrdingNo.Text = SaleOrdeNo
                ', CustomerID
                AddToDataSet(SaleOrdeNo, WriteNo, Me.CBDeliverMode.Text, Me.CBStoreCode.Text, Format(Me.DateTimePicker1.Value, "yyyy-MM-dd"), Me.cmbDept.Text, Me.cbmCustomeType.Text, fCustomerName, fLinkMan, fLinkPhone, Me.txtArea.Text, fDeliverAddress, PubCompanyCode, SaleMan, SaleDate, Me.CBOrdingMode.Text, OperateMan, OperateDate, PayMode, DSIA, DSIB, BSI, FTAmount, FReceipt, FRefund, Remark)
            ElseIf ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                'If Me.CBCustomerNo.SelectedValue Is Nothing Then
                sql = "Update Sal_SaleOrdeA Set fWriteNo='" & WriteNo & "',fDeliverMode='" & DeliverMode & "',fDeliverDate='" & fDeliverDate & "',fCustomerID='" & CustomerID & "',fCustomerName='" & fCustomerName & "',fLinkMan='" & fLinkMan & "',fLinkPhone='" & fLinkPhone & "',fDeliverAddress='" & fDeliverAddress & "',fAreaID='" & Me.LabAreaID.Text
                'sql += "',ShopNo='" & PubCompanyCode & "',fEmployeeID='" & SaleMan & "',fSaleDate='" & SaleDate & "',fOperaterMan='" & OperateMan & "',fOperateDate='" & OperateDate & "',fOrdeStatus='" & Me.CBOrdingMode.SelectedValue & "',fStorecode='" & Storecode & "',fDSIA=" & DSIA
                ''Modfies by huyang :修改不要更新 shopno
                sql += "',fEmployeeID='" & SaleMan & "',fSaleDate='" & SaleDate & "',fOperaterMan='" & OperateMan & "',fOperateDate='" & OperateDate & "',fOrdeStatus='" & Me.CBOrdingMode.SelectedValue & "',fStorecode='" & Storecode & "',fDSIA=" & DSIA
                sql += ",fDSIB=" & DSIB & ",fBSI=" & BSI & ",FTAmount=" & FTAmount & ",FRefund=" & FRefund & ",fPayMode='" & PayMode & "',fRemark='" & Remark & "',fUpdateComputer='" & My.Computer.Name & "' where fSaleOrdeNo='" & Me.LabOrdingNo.Text.Trim & "' ;"

                If CustomerType <> "Retail" Then
                    sql += " Update Sal_SaleOrdeD set  Origin = '" & Origin & "', TransportMode='" & TransportMode & "', paymentMethod='" & paymentMethod & "', PortOfLoading= '" & PortOfLoading & "', PortOfDestination='" & PortOfDestination & "', Packing='" & Packing & "', Buyer='" & Buyer & "', Saller='" & Saller & "', Insurance='" & Insurance & "', claims='" & claims & "',Arbitration='" & Arbitration & "', ForceMajeure='" & ForceMajeure & "', SourceDocPath='" & SourceDocPath & "',ShippingMarks='" & ShippingMarks & "',QtyPriceAmount= '" & QtyPriceAmount & "',SelModeOther= '" & SelModeOther & "',Other= '" & Other & "' "
                    sql += " WHERE fSaleOrdeNo='" & Me.LabOrdingNo.Text.Trim & "' "
                End If


                'Else
                '    sql = "Update Sal_SaleOrdeA Set fWriteNo='" & WriteNo & "',fDeliverMode='" & DeliverMode & "',fDeliverDate='" & fDeliverDate & "',fCustomerID='" & CustomerID & "',fAreaID='" & Me.LabAreaID.Text & "',ShopNo='" & PubCompanyCode & "',fEmployeeID='" & SaleMan & "',fSaleDate='" & SaleDate & "',fOperaterMan='" & OperateMan & _
                '                          "',fOperateDate='" & OperateDate & "',fOrdeStatus='" & Me.CBOrdingMode.SelectedValue & "',fStorecode='" & Storecode & "',fDSIA=" & DSIA & ",fDSIB=" & DSIB & ",fBSI=" & BSI & ",FTAmount=" & FTAmount & ",FRefund=" & FRefund & ",fPayMode='" & PayMode & "',fRemark='" & _
                '                          Remark & "',fUpdateComputer='" & My.Computer.Name & "' where fSaleOrdeNo='" & Me.LabOrdingNo.Text.Trim & "' ;"
                'End If
                sql += "delete Sal_SaleOrdeB where fSaleOrdeNo='" & Me.LabOrdingNo.Text.Trim & "' ;"

                With SqlCmd
                    .Connection = sqlConn
                    .Transaction = SqlTran
                    .CommandType = CommandType.Text
                    .CommandText = sql
                    .ExecuteNonQuery()
                End With
                Dim mTable As DataTable = ReturnTable(Me.LabOrdingNo.Text)
                SqlBulk = New SqlClient.SqlBulkCopy(GetConn)
                SqlBulk.DestinationTableName = "dbo.Sal_SaleOrdeB"
                SqlBulk.BulkCopyTimeout = 100
                SqlBulk.WriteToServer(mTable)


                'If Me.CBDeliverMode.SelectedIndex = 2 Then
                '    Dim InvNum As String = ""
                '    InvNum = GetValue("select dbo.GetMaxNum('SalInvoice')")
                '    SqlStr += "Insert Into Sal_InvoiceA(FNum,FDate,ShopNo,FSaleOrdeNo,FWriteNo,FType,FNeedDate,FRdeliver,FDSIA,FDSIB,FBSI,FTAmount,BillstatusID,BulidDate,BulidComputer,BulidBy) values('"
                '    SqlStr += InvNum & "','" & OperateDate & "','" & PubCompanyCode & "','" & Me.LabOrdingNo.Text & "','" & WriteNo & "','BALANCE','" & OperateDate & "',1,0.00," & Me.txtBSI.Text & ",0.00," & txtBSI.Text & ",'A','" & ServerDate & "','" & My.Computer.Name & "','" & PubUserName & "')"
                '    SqlStr += "update Number set Number=Number+1 where BillType='SalInvoice'"
                'End If


                If Me.cbmCustomeType.SelectedValue = "Retail" Then

                    SqlStr += "Update Sal_InvoiceA set FWriteNo='" & WriteNo & "',FPayInFull=0,FDSIA=" & DSIA & ",FDSIB=" & DSIB & ",FBSI=" & BSI & ",FTAmount=" & FTAmount & ",FReceipt=" & FReceipt & ",FRefund=" & FRefund & " where FNum='" & Me.LabInvNo.Text & "';"
                    SqlStr += "delete Sal_InvoiceC where FNum='" & Me.LabInvNo.Text & "'"
                    SqlStr += ReturnSqlStr(Me.LabInvNo.Text)
                    With SqlCmd
                        .Connection = sqlConn
                        .Transaction = SqlTran
                        .CommandType = CommandType.Text
                        .CommandText = SqlStr
                        .ExecuteNonQuery()
                    End With
                    ' CustomerID,
                    Me.LabInvNo.Text = InvNo

                End If
                EditToDataSet(Me.LabOrdingNo.Text.Trim, WriteNo, Me.CBDeliverMode.Text, Me.CBStoreCode.Text, Format(Me.DateTimePicker1.Value, "yyyy-MM-dd"), Me.cmbDept.Text, Me.cbmCustomeType.Text, fCustomerName, fLinkMan, fLinkPhone, Me.txtArea.Text, fDeliverAddress, PubCompanyCode, SaleMan, SaleDate, Me.CBOrdingMode.Text, OperateMan, OperateDate, PayMode, DSIA, DSIB, BSI, FTAmount, FReceipt, FRefund, Remark)
            End If
            SqlTran.Commit()
            sqlConn.Close()
            MsgBox(IIf(ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd, My.Resources.AddSuccess, My.resources.EditSuccess), MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            Me.DGV_Master.DataSource = mDatasetA.Tables(0)
            SetGridRowBackColor(Me.DGV_Master, mDatasetA)
            SetEnable(False)
            bFind = True
            MainForm.BtnEnable(bFind)
        Catch ex As Exception
            SqlTran.Rollback()
            MsgBox("BtnActionSave:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
            MsgBox(ex.Message)
        Finally
            m_Ds = Nothing
            SqlTran = Nothing
            SqlBulk = Nothing
            SqlCmd = Nothing
        End Try
        UpdateMemberMark()
    End Function

    Private Sub AddToDataSet(ByVal SaleOrdeNo As String, ByVal WriteNo As String, ByVal DeliverMode As String, ByVal StoreCode As String, ByVal fDeliverDate As String, ByVal fGoodsType As String, ByVal fCustomerType As String, ByVal CustomerName As String, ByVal LinkMan As String, ByVal LinkPhone As String, ByVal fAreaID As String, ByVal DeliverAddress As String, _
                            ByVal ShopNo As String, ByVal SaleMan As String, ByVal SaleDate As String, ByVal OrdeStatus As String, ByVal OperaterMan As String, ByVal OperateDate As String, ByVal PayMode As String, ByVal DSIA As Decimal, ByVal DSIB As Decimal, ByVal BSI As Decimal, ByVal FTAmount As Decimal, ByVal FReceipt As Decimal, ByVal FRefund As Decimal, ByVal Remark As String)
        Try
            Dim mRow As DataRow = mDatasetA.Tables(0).NewRow
            mRow("fSaleOrdeNo") = SaleOrdeNo
            mRow("fWriteNo") = WriteNo
            mRow("fDeliverMode") = DeliverMode
            mRow("fStoreCode") = StoreCode
            mRow("fDeliverDate") = fDeliverDate
            mRow("fGoodsType") = fGoodsType
            mRow("fCustomerType") = fCustomerType
            mRow("fCustomerName") = CustomerName
            mRow("fLinkMan") = LinkMan
            mRow("fLinkPhone") = LinkPhone
            mRow("fAreaID") = fAreaID
            mRow("fDeliverAddress") = DeliverAddress
            mRow("ShopNo") = ShopNo
            mRow("fEmployeeID") = SaleMan
            mRow("fSaleDate") = SaleDate
            mRow("fOrdeStatus") = OrdeStatus
            mRow("fOperaterMan") = OperaterMan
            mRow("fOperateDate") = OperateDate
            mRow("fPayMode") = PayMode
            mRow("fDSIA") = DSIA
            mRow("fDSIB") = DSIB
            mRow("fBSI") = BSI
            mRow("FTAmount") = FTAmount
            mRow("FReceipt") = FReceipt
            mRow("FRefund") = FRefund
            mRow("fRemark") = Remark
            mDatasetA.Tables(0).Rows.Add(mRow)
            mDatasetA.AcceptChanges()
        Catch ex As Exception
            MsgBox("AddToDataSet:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub EditToDataSet(ByVal SaleOrdeNo As String, ByVal WriteNo As String, ByVal DeliverMode As String, ByVal StoreCode As String, ByVal fDeliverDate As String, ByVal fGoodsType As String, ByVal fCustomerType As String, ByVal CustomerName As String, ByVal LinkMan As String, ByVal LinkPhone As String, ByVal fAreaID As String, ByVal DeliverAddress As String, _
                            ByVal ShopNo As String, ByVal SaleMan As String, ByVal SaleDate As String, ByVal OrdeStatus As String, ByVal OperaterMan As String, ByVal OperateDate As String, ByVal PayMode As String, ByVal DSIA As Decimal, ByVal DSIB As Decimal, ByVal BSI As Decimal, ByVal FTAmount As Decimal, ByVal FReceipt As Decimal, ByVal FRefund As Decimal, ByVal Remark As String)
        Try
            Dim Rows() As DataRow = mDatasetA.Tables(0).Select("fSaleOrdeNo='" & SaleOrdeNo & "'")
            If Rows.Length > 0 Then
                For Each mRow As DataRow In Rows
                    mRow("fWriteNo") = WriteNo
                    mRow("fDeliverMode") = DeliverMode
                    mRow("fStoreCode") = StoreCode
                    mRow("fDeliverDate") = fDeliverDate
                    mRow("fGoodsType") = fGoodsType
                    mRow("fCustomerType") = fCustomerType
                    mRow("fCustomerName") = CustomerName
                    mRow("fLinkMan") = LinkMan
                    mRow("fLinkPhone") = LinkPhone
                    mRow("fAreaID") = fAreaID
                    mRow("fDeliverAddress") = DeliverAddress
                    mRow("ShopNo") = ShopNo
                    mRow("fEmployeeID") = SaleMan
                    mRow("fSaleDate") = SaleDate
                    mRow("fOrdeStatus") = OrdeStatus
                    mRow("fOperaterMan") = OperaterMan
                    mRow("fOperateDate") = OperateDate
                    mRow("fPayMode") = PayMode
                    mRow("fDSIA") = DSIA
                    mRow("fDSIB") = DSIB
                    mRow("fBSI") = BSI
                    mRow("FTAmount") = FTAmount
                    mRow("FReceipt") = FReceipt
                    mRow("FRefund") = FRefund
                    mRow("fRemark") = Remark
                Next
            End If
            mDatasetA.AcceptChanges()
        Catch ex As Exception
            MsgBox("EditToDataSet:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Function DeleteFromDataBase(ByVal SaleOrdeNo As String) As Boolean
        Try
            Dim sql As String = ""
            sql = "Delete Sal_SaleOrdeA where fSaleOrdeNo='" & SaleOrdeNo & "';"
            sql += "Delete Sal_SaleOrdeB where fSaleOrdeNo='" & SaleOrdeNo & "';"
            sql += "Delete Sal_InvoiceA where fSaleOrdeNo='" & SaleOrdeNo & "'"
            ReturnObject(sql)
            Dim Rows() As DataRow = mDatasetA.Tables(0).Select("fSaleOrdeNo='" & SaleOrdeNo & "'")
            If Rows.Length > 0 Then
                mDatasetA.Tables(0).Rows.Remove(Rows(0))
            End If
            Return True
        Catch ex As Exception
            MsgBox("DeleteFromDataBase:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Private Sub JudgeGridRowNo()

        Try
            If Me.DGV_Detail.CurrentRow.Cells("ItemNo").Value Is DBNull.Value Or Me.DGV_Detail.CurrentRow.Cells("ItemNo").Value Is Nothing Then
                Me.DGV_Detail.CurrentRow.Cells("ItemNo").Value = Format(Me.DGV_Detail.Rows.Count, "000")
            Else
                Dim mCount As Integer = 0
                Dim NewCellValue As String = Me.DGV_Detail.CurrentRow.Cells("ItemNo").Value
                If NewCellValue = OldCellValue Then
                    Exit Sub
                End If
                For i As Integer = 0 To Me.DGV_Detail.Columns.Count - 1
                    If i <> 0 Then
                        If Me.DGV_Detail.Rows(RowIndex).Cells(i).Value Is DBNull.Value Then
                            mCount += 1
                        Else
                            Exit For
                        End If
                    End If
                Next
                If mCount = Me.DGV_Detail.Columns.Count - 1 Then
                    If RowIndex > 0 Then
                        Me.DGV_Detail.Rows.RemoveAt(RowIndex)
                    End If
                End If
                RowIndex = Me.DGV_Detail.CurrentRow.Index
                OldCellValue = Me.DGV_Detail.CurrentRow.Cells("ItemNo").Value
                Exit Sub
            End If
        Catch ex As Exception
            MsgBox("JudgeGridRowNo:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub SetGridRowBackColor(ByVal Grid As DataGridView, ByVal DS As DataSet)
        Try
            If DS.Tables(0).Rows.Count <= 0 Then Exit Sub

            For i As Integer = 0 To DS.Tables(0).Rows.Count - 1
                If DS.Tables(0).Rows(i).Item("fOrdeStatus").ToString = "核准" Then
                    Grid.Rows(i).DefaultCellStyle.BackColor = System.Drawing.SystemColors.Info
                ElseIf DS.Tables(0).Rows(i).Item("fOrdeStatus").ToString = "反核准" Then
                    Grid.Rows(i).DefaultCellStyle.BackColor = Color.DeepSkyBlue
                ElseIf DS.Tables(0).Rows(i).Item("fOrdeStatus").ToString = "保存" Then
                    Grid.Rows(i).DefaultCellStyle.BackColor = Color.AliceBlue
                ElseIf DS.Tables(0).Rows(i).Item("fOrdeStatus").ToString = "結案" Then
                    Grid.Rows(i).DefaultCellStyle.BackColor = Color.Gainsboro
                End If
            Next

        Catch ex As Exception
            MsgBox("SetGridRowBackColor:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    ''' 主窗體上的ToolButton按鈕的Enable屬性
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SetToolEnable()

        Dim ShopNo As String = ""
        If Not Me.DGV_Master.CurrentRow Is Nothing Then
            ShopNo = Me.DGV_Master.CurrentRow.Cells("ShopNo").Value & ""
        End If
        If Me.DGV_Master.Rows.Count > 0 Then
            If Me.DGV_Master.CurrentRow.Cells("fOrdeStatus").Value = "保存" Then
                If ShopNo = PubCompanyName Then
                    MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                    MainForm.ToolStripUnCheck.Enabled = False
                    MainForm.ToolStripComplete.Enabled = False
                    MainForm.ToolStripDelete.Enabled = True And DeleteEnable = True
                    MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                Else
                    MainForm.ToolStripCheck.Enabled = False
                    MainForm.ToolStripUnCheck.Enabled = False
                    MainForm.ToolStripComplete.Enabled = False
                    MainForm.ToolStripDelete.Enabled = False
                    MainForm.ToolStripEdit.Enabled = False
                End If
                Me.BtnCancel.Enabled = False
            ElseIf Me.DGV_Master.CurrentRow.Cells("fOrdeStatus").Value = "核准" Then
                MainForm.ToolStripCheck.Enabled = False
                MainForm.ToolStripUnCheck.Enabled = True And UncheckEnable = True
                MainForm.ToolStripComplete.Enabled = True And CompleteEnable = True
                MainForm.ToolStripDelete.Enabled = False
                MainForm.ToolStripEdit.Enabled = False
                Me.BtnCancel.Enabled = True
            ElseIf Me.DGV_Master.CurrentRow.Cells("fOrdeStatus").Value = "反核准" Then
                MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                MainForm.ToolStripUnCheck.Enabled = False
                MainForm.ToolStripComplete.Enabled = False
                MainForm.ToolStripDelete.Enabled = False
                MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                Me.BtnCancel.Enabled = True
            ElseIf Me.DGV_Master.CurrentRow.Cells("fOrdeStatus").Value = "結案" Then
                MainForm.ToolStripCheck.Enabled = False
                MainForm.ToolStripUnCheck.Enabled = False
                MainForm.ToolStripComplete.Enabled = False
                MainForm.ToolStripDelete.Enabled = False
                MainForm.ToolStripEdit.Enabled = False
                Me.BtnCancel.Enabled = False
            End If
            If Me.DGV_Master.CurrentRow.Index = 0 Then
                MainForm.ToolStripFirst.Enabled = False
                MainForm.ToolStripNext.Enabled = True
                MainForm.ToolStripPrivous.Enabled = False
                MainForm.ToolStripLast.Enabled = True
            ElseIf Me.DGV_Master.CurrentRow.Index = Me.DGV_Master.Rows.Count - 1 Then
                MainForm.ToolStripFirst.Enabled = True
                MainForm.ToolStripNext.Enabled = False
                MainForm.ToolStripPrivous.Enabled = True
                MainForm.ToolStripLast.Enabled = False
            Else
                MainForm.ToolStripFirst.Enabled = True
                MainForm.ToolStripNext.Enabled = True
                MainForm.ToolStripPrivous.Enabled = True
                MainForm.ToolStripLast.Enabled = True
            End If
            MainForm.ToolStripPrint.Enabled = True
        End If

    End Sub

#End Region


#Region "Control Events"

    Private Sub GetToolEnable()
        Try
            With MainForm
                .ToolStripAdd.Enabled = AddEnable
                .ToolStripEdit.Enabled = EditEnable And bFind = True
                .ToolStripDelete.Enabled = DeleteEnable And bFind = True
                .ToolStripPrint.Enabled = PrintEnable
                .ToolStripImport.Enabled = ImportEnable
                .ToolStripExport.Enabled = ExportEnable
                .ToolStripFind.Enabled = FindEnable
                .ToolStripCheck.Enabled = CheckEnable
                .ToolStripUnCheck.Enabled = UncheckEnable
                .ToolStripComplete.Enabled = CompleteEnable
                .AddToolStripMenuItem.Enabled = .ToolStripAdd.Enabled
                .Edit1ToolStripMenuItem.Enabled = .ToolStripEdit.Enabled
                .DelToolStripMenuItem.Enabled = .ToolStripDelete.Enabled
                .SaveToolStripMenuItem.Enabled = .ToolStripSave.Enabled
                .CancelToolStripMenuItem.Enabled = .ToolStripCancel.Enabled
                .PrintToolStripMenuItem.Enabled = .ToolStripPrint.Enabled
                .ExportToolStripMenuItem.Enabled = .ToolStripImport.Enabled
                .ImportToolStripMenuItem.Enabled = .ToolStripExport.Enabled
                .FilterToolStripMenuItem.Enabled = .ToolStripFilter.Enabled
            End With

        Catch ex As Exception
            MsgBox("GetToolEnable:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub Frm_SALRetailSC_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            LoadBasicData()
            LoadCurrency()
            BindDataSetA()
            BindDataSetB()
            BindDataSetC()
            LoadGifSet()
            LoadMemberPerson()
            LoadSalesPromotionSet()
            SetEnable(False)
            SetGridCaptionVisible(Me.DGV_Master, Fields, "Frm_SALRetailSC")
            LoadGoods()
            Me.ComboBox1.Enabled = False
            ComBox.Visible = False
            Me.DGV_PayMode.Controls.Add(ComBox)
            If UncheckEnable = True Then
                Me.BtnCancel.Visible = True
            Else
                Me.BtnCancel.Visible = False
            End If

            Me.BtnFind.Enabled = FindEnable
        Catch ex As Exception
            MsgBox(My.Resources.LoadFormError, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub txtArea_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtArea.DoubleClick, BtnArea.Click
        Try
            'Dim Frm_SelectArea As New Frm_SelectArea
            'Frm_SelectArea.ShowDialog()
            'Me.txtArea.Text = Frm_SelectArea.AreaStr
            'Me.LabAreaID.Text = Frm_SelectArea.AreaID
            Dim frm As New frm_AreaSelect
            frm.DependDate = DateTimePicker1.Text
            frm.SummaryDept = cmbDept.Text.Trim
            If Not cmbDept.SelectedValue Is Nothing Then
                frm.DependDept = cmbDept.SelectedValue
            End If

            If frm.ShowDialog = DialogResult.OK Then
                Dim dgv As DataGridView = frm.DGView1
                If dgv.SelectedRows.Count > 0 Then
                    Me.txtArea.Text = dgv.SelectedRows(0).Cells("AreaName").Value & ""
                    Me.LabAreaID.Text = dgv.SelectedRows(0).Cells("Id").Value & ""
                End If
            End If
        Catch ex As Exception
            MsgBox("txtDliveraddress_DoubleClick" & ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub txtCustomeRemark_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtCustomeRemark.DoubleClick

        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Dim FrmDes As New Frm_Description
                FrmDes.ShowDialog()
                If FrmDes.Description Is Nothing Then
                    Exit Sub
                End If
                Me.txtCustomeRemark.Text += FrmDes.Description.ToString
            End If
        Catch ex As Exception
            MsgBox("txtCustomeRemark_DoubleClick:" & ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub txtWriteNo_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtWriteNo.KeyDown, txtSaleDate.KeyDown, CBCustomerNo.KeyDown, txtDliveraddress.KeyDown, CBDeliverMode.KeyDown, txtReciveman.KeyDown, txtCustomePhone.KeyDown, txtCustomeRemark.KeyDown, txtSumDSI.KeyDown, txtSumDSIA.KeyDown, txtBSI.KeyDown, CBSaleman.KeyDown, CBOrdingMode.KeyDown, CBStoreCode.KeyDown
        Try
            If e.KeyCode = Keys.Shift Then
                e.Handled = True
                If e.KeyCode = Keys.Enter Then
                    SendKeys.Send("+{TAB}")
                    SendKeys.Send("{F4}")
                End If
            Else
                Select Case e.KeyCode
                    Case Keys.Enter
                        e.Handled = True
                        If sender.name = "txtWriteNo" Then
                            Me.CBSaleman.Focus()
                            SendKeys.Send("{F4}")
                        ElseIf sender.name = "CBSaleman" Then
                            Me.CBOrdingMode.Focus()
                            SendKeys.Send("{F4}")
                        ElseIf sender.name = "CBOrdingMode" Then
                            Me.CBStoreCode.Focus()
                            SendKeys.Send("{F4}")
                        ElseIf sender.name = "CBCustomerNo" Then
                            Me.txtDliveraddress.Focus()
                            SendKeys.Send("{F4}")
                        ElseIf sender.name = "CBDeliverMode" Then
                            Me.txtReciveman.Focus()
                            SendKeys.Send("{F4}")
                        Else
                            SendKeys.Send("{TAB}")
                            SendKeys.Send("{F4}")
                        End If
                    Case Keys.F1

                End Select
            End If
        Catch ex As Exception
            MsgBox("txtWriteNo_KeyDown:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub DGV_Master_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_Master.CellClick
        SetToolEnable()
    End Sub

    Private Sub DGV_Master_ColumnWidthChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles DGV_Master.ColumnWidthChanged
        SetGridWidth(1)
    End Sub

    Private Sub DataGridView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGV_Master.DoubleClick
        If Me.TabControl1.SelectedIndex = 0 Then
            Me.TabControl1.SelectedIndex = 1
        End If
    End Sub

    Private Sub TabControl1_Selected(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlEventArgs) Handles TabControl1.Selected

        Try
            If Not Me.TabControl1.SelectedTab Is Nothing Then
                Select Case Me.TabControl1.SelectedIndex
                    Case 0
                        Me.WriteNo.Text = ""
                        Me.GoodsName.Text = ""
                        Me.DeliverType.Text = ""
                        Me.SaleMan.Text = ""
                        Me.OrdeMode.Text = ""
                        Me.OrdeShopNo.Text = ""
                        Me.txtOrdeType.Text = ""
                        Me.TextBoxShow.Text = ""
                    Case 1
                        If mDatasetA.Tables(0).Rows.Count <= 0 Then
                        Else
                            Dim SaleOrdeNo As String = Me.DGV_Master.CurrentRow.Cells("fSaleOrdeNo").Value & ""
                            FillText(SaleOrdeNo)
                            Me.TextBoxShow.Text = ""
                        End If
                End Select
            End If

        Catch ex As Exception
            MsgBox("TabControl1_Selected:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub TabControl1_Selecting(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlCancelEventArgs) Handles TabControl1.Selecting

        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                e.Cancel = True
            End If
        Catch ex As Exception
            MsgBox("TabControl1_Selecting:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub BtnFind_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnFind.Click
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim sql As String = ""
            Dim WhereStr As String = ""
            If Me.SaleOrdingNo.Text.Length > 0 Then
                WhereStr += " and fSaleOrdeNo='" & Me.SaleOrdingNo.Text.Trim & "'"
            End If
            If Me.WriteNo.Text.Length > 0 Then
                WhereStr += " and fWriteNo='" & Me.WriteNo.Text.Trim & "'"
            End If
            If Me.OrdeMode.Text.Trim <> "" Then
                WhereStr += " and fOrdeStatus = '" & Me.OrdeMode.Text & "'"
            End If
            If Me.SaleMan.Text.Trim <> "" Then
                WhereStr += " and fEmployeeID like '%" & Me.SaleMan.Text & "%'"
            End If

            If Me.OrderCustomerType.Text.Trim <> "" Then
                WhereStr += " and fCustomerType = '" & Me.OrderCustomerType.Text & "' "
            End If

            If Me.txtOrdeType.Text.Length > 0 Then

                Dim OrdeType1 As String = Me.txtOrdeType.Text

                If OrdeType1.EndsWith(",") Then
                    OrdeType1 = OrdeType1.Remove(OrdeType1.Length - 1, 1)
                End If

                Dim Str() As String = OrdeType1.Split(",")
                Dim OrdeType As String = ""

                For i As Int64 = 0 To Str.Length - 1
                    OrdeType += "'" & Str(i) & "',"
                Next
                If OrdeType.EndsWith(",") Then
                    OrdeType = OrdeType.Remove(OrdeType.Length - 1, 1)
                End If

                WhereStr += " and fGoodsType in (" & OrdeType & ")"
            End If

            If Me.OrdeShopNo.Text.Trim <> "" Then
                WhereStr += " and ShopNo like '%" & Me.OrdeShopNo.Text & "%'"
            End If

            If Me.DeliverType.Text.Trim <> "" Then
                WhereStr += " and fDeliverMode like '%" & Me.DeliverType.Text & "%'"
            End If

            If Me.StartDate.Value.ToString.Length > 0 And Me.EndDate.Value.ToString.Length <= 0 Then
                'WhereStr += " and fSaleDate"
            ElseIf Me.StartDate.Value.ToString.Length <= 0 And Me.EndDate.Value.ToString.Length >= 0 Then
                'WhereStr += " and fSaleDate"
            ElseIf Me.StartDate.Value.ToString.Length >= 0 And Me.EndDate.Value.ToString.Length >= 0 Then
                WhereStr += " and fSaleDate between '" & Format(Me.StartDate.Value, "yyyy-MM-dd") & "' and '" & Format(Me.EndDate.Value, "yyyy-MM-dd") & "'"
            End If
            sql = "select fSaleOrdeNo, fWriteNo, fDeliverMode, fStoreCode, fDeliverDate, fGoodsType, fcustomerType,fCustomerName, fLinkMan, fLinkPhone, fAreaID, fDeliverAddress, ShopNo, fEmployeeId, fSaleDate, fOperaterMan, fOperateDate, fCheckMan, fCheckDate, fOrdeStatus, isnull(FDSIA,0) as FDSIA, isnull(FDSIB,0) as FDSIB, isnull(FBSI,0) as FBSI, isnull(FTAmount,0)  as FTAmount, isnull(FReceipt,0) as FReceipt, isnull(FRefund,0) as FRefund, fPayMode, fRemark  from V_SaleOrde where 1=1" & WhereStr
            mDatasetA = ReturnDataset(sql)

            Me.DGV_Master.DataSource = mDatasetA.Tables(0)
            bFind = mDatasetA.Tables(0).Rows.Count > 0
            If mDatasetA.Tables(0).Rows.Count > 0 Then
                MainForm.ToolStripFirst.Enabled = False
                MainForm.ToolStripNext.Enabled = True
                MainForm.ToolStripPrivous.Enabled = False
                MainForm.ToolStripLast.Enabled = True
                Me.DGV_Master.CurrentCell = Me.DGV_Master.Rows(0).Cells(0)
            Else
                MainForm.ToolStripFirst.Enabled = False
                MainForm.ToolStripNext.Enabled = False
                MainForm.ToolStripPrivous.Enabled = False
                MainForm.ToolStripLast.Enabled = False
            End If

            If Me.DGV_Master.Rows.Count > 0 Then
                Me.DGV_MasterSum.Rows(0).Cells("fDSIA").Value = Format(Val(mDatasetA.Tables(0).Compute("sum(fDSIA)", "")), "#0.00")
                Me.DGV_MasterSum.Rows(0).Cells("FDSIB").Value = Format(Val(mDatasetA.Tables(0).Compute("sum(FDSIB)", "")), "#0.00")
                Me.DGV_MasterSum.Rows(0).Cells("fBSI").Value = Format(Val(mDatasetA.Tables(0).Compute("sum(fBSI)", "")), "#0.00")
                Me.DGV_MasterSum.Rows(0).Cells("FTAmount").Value = Format(Val(mDatasetA.Tables(0).Compute("sum(FTAmount)", "")), "#0.00")
                Me.DGV_MasterSum.Rows(0).Cells("FReceipt").Value = Format(Val(mDatasetA.Tables(0).Compute("sum(FReceipt)", "")), "#0.00")
                Me.DGV_MasterSum.Rows(0).Cells("FRefund").Value = Format(Val(mDatasetA.Tables(0).Compute("sum(FRefund)", "")), "#0.00")
            End If
            '' SetGridRowBackColor(Me.DGV_Master, mDatasetA)
            ''GetToolEnable()
            SetToolEnable()
        Catch ex As Exception
            ''MsgBox("BtnFind_Click:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub
    Private Function GetMasterBarCode(ByVal BarCode As String)
        Dim MasterBarCode As String = ""

        Dim sql As String = " select Replace(BarCode,'*','') as BarCode from BSC_BarCode where Replace(SuppBarCode,'*','')='" & BarCode & "' "

        MasterBarCode = Exec(sql, E_ExecType.ExecuteScalar) & ""

        Return MasterBarCode
    End Function
    Private Sub DGV_Detail_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_Detail.CellDoubleClick

        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If e.ColumnIndex = 1 Then
                    If Me.cmbDept.SelectedIndex <= -1 Then
                        MsgBox("請先選擇貨品類別！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        Me.cmbDept.Focus()
                        SendKeys.Send("{F4}")
                        Exit Sub
                    End If
                    Dim whereStr As String = Me.cmbDept.SelectedValue.ToString
                    Dim Frm_SelectGoods As New Frm_SelectGoods
                    Frm_SelectGoods.Index = 2
                    Frm_SelectGoods.WhereStr = whereStr
                    Frm_SelectGoods.ShowDialog()
                    If Frm_SelectGoods.BarCode Is Nothing Then
                        Exit Sub
                    End If
                    Dim BarCode As String = Frm_SelectGoods.BarCode
                    If BarCode.Length <= 0 Then Exit Sub
                    Dim Str() As String = BarCode.Split("^")
                    Dim Rows() As DataRow
                    For i As Integer = 0 To Str.Length - 1
                        If Str(i).ToString.Trim = "" Then
                            Exit For
                        End If
                        Rows = dsGoods.Tables(0).Select("fGoodsBarCode='" & Str(i) & "'")
                        If Rows.Length > 0 Then
                            Dim Rows1() As DataRow = mDatasetB.Tables(0).Select("fGoodsBarCode='" & Str(i) & "'")
                            If Rows1.Length > 0 Then
                            Else
                                Dim NewRow As DataRow = mDatasetB.Tables(0).NewRow
                                NewRow("ItemNo") = Format(mDatasetB.Tables(0).Rows.Count + 1, "000")
                                NewRow("fGoodsBarCode") = Rows(0).Item("fGoodsBarCode") & ""
                                NewRow("Code") = Rows(0).Item("Code") & ""
                                NewRow("Enname") = Rows(0).Item("Enname") & ""
                                NewRow("Cnname") = Rows(0).Item("Cnname") & ""
                                NewRow("fGoodsColor") = Rows(0).Item("fGoodsColor") & ""
                                NewRow("fGoodsSize") = Rows(0).Item("fGoodsSize") & ""
                                mDatasetB.Tables(0).Rows.Add(NewRow)
                            End If
                        Else
                            Dim MasterBarCode As String = GetMasterBarCode(Str(i))
                            If MasterBarCode = "" Then Exit Sub
                            Rows = mDataset.Tables(0).Select("BarCode='*" & MasterBarCode & "*'")
                            If Rows.Length > 0 Then
                                Dim NewRow As DataRow = mDatasetB.Tables(0).NewRow
                                NewRow("ItemNo") = Format(mDatasetB.Tables(0).Rows.Count + 1, "000")
                                NewRow("fGoodsBarCode") = Rows(0).Item("fGoodsBarCode") & ""
                                NewRow("Code") = Rows(0).Item("Code") & ""
                                NewRow("Enname") = Rows(0).Item("Enname") & ""
                                NewRow("Cnname") = Rows(0).Item("Cnname") & ""
                                NewRow("fGoodsColor") = Rows(0).Item("fGoodsColor") & ""
                                NewRow("fGoodsSize") = Rows(0).Item("fGoodsSize") & ""
                                mDatasetB.Tables(0).Rows.Add(NewRow)
                            End If
                            If Str(i).Length > 0 Then
                                MsgBox("對不起，貨品 [" & Str(i) & "] 不存在或類型不匹配！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                            End If
                        End If
                    Next
                    mDatasetB.AcceptChanges()
                    Me.DGV_Detail.DataSource = mDatasetB.Tables(0)
                    Me.DGV_Detail.AllowUserToAddRows = False
                    For i As Integer = 0 To Me.DGV_Detail.Rows.Count - 1
                        If Me.DGV_Detail.Rows(i).Cells("ItemNo").Value Is DBNull.Value Or Me.DGV_Detail.Rows(i).Cells("ItemNo") Is Nothing Then
                            Me.DGV_Detail.Rows.RemoveAt(i)
                            Exit For
                        End If
                    Next
                ElseIf e.ColumnIndex = 10 Then
                    Dim FrmDes As New Frm_Description
                    AddHandler FrmDes.SelectRows, AddressOf FillDataGridView
                    FrmDes.ShowDialog()
                    'Me.DGV_Detail.CurrentRow.Cells(e.ColumnIndex).Value = FrmDes.Description.ToString
                End If
            End If
        Catch ex As Exception
            MsgBox("DGV_Detail_CellDoubleClick:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub FillDataGridView(ByVal mRemark As String)

        Try
            Me.DGV_Detail.CurrentRow.Cells(Me.DGV_Detail.CurrentCell.ColumnIndex).Value += mRemark
        Catch ex As Exception
            MsgBox("FillDataGridView:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub DGV_Detail_CellValidated(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_Detail.CellValidated

        Try
            Me.DGV_Detail.Rows(e.RowIndex).ErrorText = Nothing
        Catch ex As Exception
            MsgBox("DGV_Detail_CellValidated:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub DGV_Detail_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DGV_Detail.CellValidating

        Try
            If e.ColumnIndex = 7 Then
                Dim testInteger As Double
                If Me.DGV_Detail.CurrentRow.IsNewRow Then
                    Exit Sub
                End If
                If Not e.FormattedValue.ToString.Length = 0 Then
                    If Not Double.TryParse(e.FormattedValue.ToString, testInteger) Then
                        Me.DGV_Detail.Rows(e.RowIndex).ErrorText = ""
                        e.Cancel = True
                    End If
                Else
                    e.Cancel = True
                End If
            End If
        Catch ex As Exception
            MsgBox("DGV_Detail_CellValidating:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub DGV_Detail_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_Detail.CellValueChanged

        Dim mDs As New DataSet
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Dim mCount As Double
                Dim GoodsSalePrice As Double
                Dim BarCode As String = ""
                Dim sql As String = ""
                Dim ValideDate As Date
                If e.ColumnIndex = 7 Then
                    If mDatasetB.Tables(0).Rows.Count > 0 Then
                        BarCode = Me.DGV_Detail.CurrentRow.Cells("fGoodsBarCode").Value & ""
                        mCount = Double.Parse(Me.DGV_Detail.CurrentRow.Cells("fSumCount").Value.ToString)
                        'sql = "select BarCode,ValidDate,SalePrice from Goods_SalePrice where Barcode='*" & BarCode & "*'"
                        'mDs = ReturnDataset(sql)
                        sql = " select top 1 Isnull(SalePrice,0) as SalePrice ,BarCode,ValidDate from Goods_SalePrice where Barcode='*" & BarCode & "*' and Convert(varchar(10),ValidDate,21)<=Convert(varchar(10),getdate(),21) order by ValidDate desc   "
                        mDs = ReturnDataset(sql)


                        If mDs.Tables(0).Rows.Count > 0 Then
                            For i As Integer = 0 To mDs.Tables(0).Rows.Count - 1
                                ValideDate = CType(mDs.Tables(0).Rows(i).Item("ValidDate"), Date)
                                If CType(ServerDate, Date) <= ValideDate Then
                                    GoodsSalePrice = mDs.Tables(0).Rows(i).Item("SalePrice")
                                    Exit For
                                Else
                                    GoodsSalePrice = 0
                                End If
                            Next
                            If GoodsSalePrice = 0 Then
                                GoTo A
                            End If
                        Else
A:
                            'GoodsSalePrice = 0
                            ''如果沒有設置銷售價則使用單價,否則GoodsSalePrice = 0
                            sql = "select Isnull(Price,0) from bsc_goods where Barcode='*" & BarCode & "*'"
                            Dim obj As Object = Exec(sql, E_ExecType.ExecuteScalar)
                            If obj Is Nothing Then
                                GoodsSalePrice = 0
                            Else
                                'GoodsSalePrice = Val(obj)

                            End If
                        End If
                        BarCodeScanInput()
                        'Dim Rows() As DataRow = dsGoods.Tables(0).Select("fGoodsBarCode='" & BarCode & "'")
                        'If Rows.Length > 0 Then
                        '    GoodsSalePrice = Double.Parse(Rows(0).Item("SalePrice"))
                        'End If



                        'Dim mCount As Double
                        'mCount = Double.Parse(Me.DGV_Detail.CurrentRow.Cells("fSumCount").Value.ToString)
                        'Me.DGV_Detail.CurrentRow.Cells("SalePrice").Value = Format(GoodsSalePrice, "#0.00")
                        'Me.DGV_Detail.CurrentRow.Cells("fSumMoney").Value = Format((mCount * GoodsSalePrice), "#0.00")

                        'Me.DGV_Sum.Rows(0).Cells("fSumCount").Value = Format(mDatasetB.Tables(0).Compute("sum(fSumCount)", ""), "#0.00")
                        ''Me.DGV_Sum.Rows(0).Cells("fGoodsPrice").Value = Format(mDatasetB.Tables(0).Compute("sum(fGoodsPrice)", ""), "#0.00")
                        'Me.DGV_Sum.Rows(0).Cells("fSumMoney").Value = Format(mDatasetB.Tables(0).Compute("sum(fSumMoney)", ""), "#0.00")
                        'Me.txtSumDSIA.Text = Format(Format(mDatasetB.Tables(0).Compute("sum(fSumMoney)", ""), "#0.00") * (Me.NumericUpDown2.Value / 100) * (Me.NumericUpDown1.Value / 100), "#0.00")
                        'Me.txtBSI.Text = Format(Format(mDatasetB.Tables(0).Compute("sum(fSumMoney)", ""), "#0.00") - (Me.txtSumDSIA.Text), "#0.00")
                        'Me.txtFTAmount.Text = Format(mDatasetB.Tables(0).Compute("sum(fSumMoney)", ""), "#0.00")
                        'Me.txtActualAmount.Text = Format(Format(mDatasetB.Tables(0).Compute("sum(fSumMoney)", ""), "#0.00") * (Me.NumericUpDown2.Value / 100) * (Me.NumericUpDown1.Value / 100), "#0.00")
                    End If
                End If
            End If

        Catch ex As Exception
            MsgBox("DGV_Detail_CellValueChanged:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub


    Private Sub BarCodeScanInput()
        Try

            Dim fQuanty As Integer = Me.DGV_Detail.CurrentRow.Cells("fsumcount").Value & "" ''數量
            If fQuanty <= 0 Then
                fQuanty = 1
            End If

            Dim mDs As New DataSet
            Dim BarCode As String = Me.DGV_Detail.CurrentRow.Cells("fGoodsBarCode").Value & ""
            Dim Rows() As DataRow = dsGoods.Tables(0).Select("fGoodsBarCode='" & BarCode & "'")

            'If Rows.Length <= 0 Then Exit Sub

            ''1.查找貨品當前銷售價格
            Dim fGoodsSalePrice As Double = Val(Rows(0).Item("SalePrice"))
            Dim currentSalePrice As Double = GetCurrentSalefPrice(BarCode)
            If currentSalePrice > 0 Then
                fGoodsSalePrice = currentSalePrice
            End If



            ''2.叛斷是否有促銷價
            Dim PromotionRows() As DataRow = DSSalesPromotion.Tables(0).Select("BarCode='*" & BarCode & "*'  and  PromotionType<>'套裝優惠'   and GoodsType<>'贈送品'", "Num desc") ''套裝優惠 單獨處理  贈送品不能算是促銷

            If PromotionRows.Length > 0 Then ''同一貨品在同一時間最好只有一種促銷方案

                Dim Num As String = PromotionRows(0).Item("Num") & ""
                Dim PromotionType As String = PromotionRows(0).Item("PromotionType") & "" ''方案類型
                Dim IsSame As Boolean = CType(PromotionRows(0).Item("IsSame"), Boolean) ''統一折扣
                'Dim Dept As String = PromotionRows(0).Item("Dept") & "" ''門店
                Dim DiscountA As Double = Val(PromotionRows(0).Item("DiscountA") & "") * 0.01 ''折扣率(%)
                Dim ReduceA As Double = Val(PromotionRows(0).Item("ReduceA") & "") ''折扣金額
                Dim PurQtyA As Integer = Val(PromotionRows(0).Item("PurQtyA") & "") ''購買量
                Dim PresentA As Integer = Val(PromotionRows(0).Item("PresentA") & "") ''贈送量

                Dim DiscountB As Double = Val(PromotionRows(0).Item("DiscountB") & "") * 0.01 ''折扣率(%)
                Dim ReduceB As Double = Val(PromotionRows(0).Item("ReduceB") & "") ''折扣金額
                Dim PurQtyB As Integer = Val(PromotionRows(0).Item("PurQtyB") & "") ''購買量
                Dim PresentB As Integer = Val(PromotionRows(0).Item("PresentB") & "") ''贈送量

                Select Case PromotionType

                    Case "一般折扣"

                        Dim IsDiscount As Boolean = False

                        If IsSame = True Then
                            If DiscountA > 0 Then
                                fGoodsSalePrice = fGoodsSalePrice * DiscountA
                                IsDiscount = True
                            Else
                                fGoodsSalePrice = fGoodsSalePrice - ReduceA
                            End If
                        Else
                            If DiscountB > 0 Then
                                fGoodsSalePrice = fGoodsSalePrice * DiscountB
                                IsDiscount = True
                            Else
                                fGoodsSalePrice = fGoodsSalePrice - ReduceB
                            End If
                        End If
                        GoodsSalePrice = fGoodsSalePrice
                        Dim currentRows() As DataRow

                        currentRows = mDatasetB.Tables(0).Select("fGoodsBarCode='" & BarCode & "'  and SalePrice > 0")
                        If currentRows.Length > 0 Then
                            Dim fAmount As Integer = (currentRows(0).Item("fSumCount") & "") + fQuanty
                            currentRows(0).Item("fSumCount") = Format(fAmount, "#0.00")
                            currentRows(0).Item("fSumMoney") = Format(fAmount * fGoodsSalePrice, "#0.00")
                        Else
                            ''AddBarCodeToTable(BarCode, Rows, fGoodsSalePrice, fQuanty)
                            If IsDiscount = True Then
                                Me.TextBoxShow.Text += String.Format(Rows(0).Item("Code") & "享受{0}拆的促銷折扣。" & System.Environment.NewLine, IIf(IsSame = True, DiscountA * 10, DiscountB * 10))
                            Else
                                Me.TextBoxShow.Text += String.Format(Rows(0).Item("Code") & "享受{0}促銷現金折扣。" & System.Environment.NewLine, IIf(IsSame = True, ReduceA, ReduceB))
                            End If

                        End If
                        mDatasetB.Tables(0).AcceptChanges()


                    Case "買幾送幾"

                        ''添加主貨品
                        GoodsSalePrice = fGoodsSalePrice
                        Dim currentRows() As DataRow
                        currentRows = mDatasetB.Tables(0).Select("fGoodsBarCode='" & BarCode & "'")
                        If currentRows.Length > 0 Then
                            Dim fAmount As Integer = (currentRows(0).Item("fSumCount") & "") ''+ fQuanty
                            currentRows(0).Item("fSumCount") = Format(fAmount, "#0.00")
                            currentRows(0).Item("fSumMoney") = Format(fAmount * fGoodsSalePrice, "#0.00")
                            currentRows(0).AcceptChanges()
                        Else
                            'AddBarCodeToTable(BarCode, Rows, fGoodsSalePrice, fQuanty)
                        End If

                        Dim purcherQuanty As Integer = Val(mDatasetB.Tables(0).Compute("sum(fSumCount)", "fGoodsBarCode='" & BarCode & "' and fSumMoney >0") & "")
                        Dim needQuanty As Integer = 0
                        Dim sendQuanty As Integer = 0

                        If IsSame = True Then
                            needQuanty = PurQtyA
                            sendQuanty = PresentA
                        Else
                            needQuanty = PurQtyB
                            sendQuanty = PresentB
                        End If
                        Dim Quanty As Integer = 0
                        Quanty = purcherQuanty \ needQuanty
                        If needQuanty > 0 AndAlso Quanty > 0 AndAlso sendQuanty > 0 Then

                            Dim fAmount As Integer = Quanty - (Val(mDatasetB.Tables(0).Compute("sum(fSumCount)", "fGoodsBarCode='" & BarCode & "'  and SalePrice=0") & "") \ sendQuanty)

                            'For i As Integer = 0 To Quanty

                            ''添加贈品
                            If Quanty > 0 AndAlso fAmount > 0 Then
                                Dim PRows() As DataRow = mDatasetB.Tables(0).Select("fGoodsBarCode='" & BarCode & "'  and SalePrice=0")

                                If PRows.Length > 0 Then
                                    PRows(0).Item("fSumCount") = Format(Quanty * sendQuanty, "#0.00")
                                    PRows(0).Item("fSumMoney") = Format(0, "#0.00")
                                Else
                                    AddBarCodeToTable(BarCode, Rows, 0, Quanty * sendQuanty, True)
                                    Dim key As String = "買幾送幾:" & Rows(0).Item("Code") & ""
                                    Me.TextBoxShow.Text += String.Format("{0} 購買滿{1}個,贈送{2}個。" & System.Environment.NewLine, key, needQuanty, sendQuanty)

                                End If
                            End If
                        End If
                        mDatasetB.Tables(0).AcceptChanges()


                    Case "買A送B"

                        ''添加主貨品
                        GoodsSalePrice = fGoodsSalePrice
                        Dim currentRows() As DataRow
                        currentRows = mDatasetB.Tables(0).Select("fGoodsBarCode='" & BarCode & "'")
                        If currentRows.Length > 0 Then
                            Dim fAmount As Integer = (currentRows(0).Item("fSumCount") & "") ''+ fQuanty
                            currentRows(0).Item("fSumCount") = Format(fAmount, "#0.00")
                            currentRows(0).Item("fSumMoney") = Format(fAmount * fGoodsSalePrice, "#0.00")
                            currentRows(0).AcceptChanges()
                        Else
                            'AddBarCodeToTable(BarCode, Rows, fGoodsSalePrice, fQuanty)
                        End If

                        ''添加贈品
                        Dim purcherQuanty As Integer = Val(mDatasetB.Tables(0).Compute("sum(fSumCount)", "fGoodsBarCode='" & BarCode & "' and fSumMoney >0") & "")
                        Dim needQuanty As Integer = 0
                        Dim sendQuanty As Integer = 0

                        If IsSame = True Then
                            needQuanty = PurQtyA
                            sendQuanty = PresentA
                        Else
                            needQuanty = PurQtyB
                            sendQuanty = PresentB
                        End If
                        Dim Quanty As Integer = 0

                        Dim subBarCode As String = ""
                        ''取得贈品編碼
                        Dim PRows() As DataRow = DSSalesPromotion.Tables(0).Select("Num='" & Num & "'  and  PromotionType<>'套裝優惠'   and GoodsType='贈送品'")
                        For Each row As DataRow In PRows
                            If PRows.Length > 0 Then
                                subBarCode = row("BarCode").ToString
                                subBarCode = subBarCode.Replace("*", "")
                            End If
                            If IsSame = True Then
                                needQuanty = PurQtyA
                                sendQuanty = PresentA
                            Else '如果不使用同一折扣
                                needQuanty = PurQtyB '主貨品
                                sendQuanty = row("PresentB").ToString
                            End If

                            Quanty = purcherQuanty \ needQuanty
                            If needQuanty > 0 AndAlso Quanty > 0 AndAlso sendQuanty > 0 AndAlso subBarCode.Length > 0 Then
                                Dim fAmount As Integer = Quanty - (Val(mDatasetB.Tables(0).Compute("sum(fSumCount)", "fGoodsBarCode='" & BarCode & "'and fSumMoney=0") & "") \ sendQuanty)
                                If Quanty > 0 AndAlso fAmount > 0 Then
                                    Dim MRows() As DataRow = mDatasetB.Tables(0).Select("fGoodsBarCode='" & subBarCode & "'  and fSumMoney=0")
                                    If MRows.Length > 0 Then
                                        MRows(0).Item("fSumCount") = Format(Quanty * sendQuanty, "#0.00")
                                        MRows(0).Item("fSumMoney") = Format(0, "#0.00")
                                    Else
                                        Dim QRows() As DataRow = dsGoods.Tables(0).Select("fGoodsBarCode='" & subBarCode & "'")
                                        If QRows.Length > 0 Then
                                            AddBarCodeToTable(subBarCode.Replace("*", ""), QRows, 0, Quanty * sendQuanty, True)
                                            Me.TextBoxShow.Text += String.Format("購買{0}," & System.Environment.NewLine, Rows(0).Item("Code") & "")
                                            Me.TextBoxShow.Text += String.Format("贈送{0}" & System.Environment.NewLine, QRows(0).Item("Code") & "")
                                        End If
                                    End If
                                End If
                            End If

                        Next

                    Case Else
                        ''未知的方案
                        GoTo A

                End Select

            Else

A:
                ''三)是否是會員

                Dim fMemberRate As Double = 1.0 ''會員折扣率

                If Me.CBCustomerNo.Text.Trim <> "" Then
                    Dim RowArray() As DataRow = DSMember.Tables(0).Select("Code='" & Me.CBCustomerNo.Text & "'")
                    If RowArray.Length > 0 Then
                        fMemberRate = Val(RowArray(0).Item("Rat") & "")
                    End If
                End If
                fGoodsSalePrice = fGoodsSalePrice * fMemberRate
                GoodsSalePrice = fGoodsSalePrice
                Dim currentRows() As DataRow
                currentRows = mDatasetB.Tables(0).Select("fGoodsBarCode='" & BarCode & "'  and SalePrice>0")
                If currentRows.Length > 0 Then
                    Dim fAmount As Integer = (currentRows(0).Item("fSumCount") & "") + fQuanty
                    currentRows(0).Item("fSumCount") = Format(fAmount, "#0.00")
                    currentRows(0).Item("fSumMoney") = Format(fAmount * fGoodsSalePrice, "#0.00")
                Else
                    'AddBarCodeToTable(BarCode, Rows, fGoodsSalePrice, fQuanty)
                End If

            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message + ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            'mDatasetB.Tables(0).AcceptChanges()
            'Me.DGV_Detail.DataSource = mDatasetB.Tables(0)
            'Me.txtFTAmount.Text = Val(mDatasetB.Tables(0).Compute("sum(fSumMoney)", "") & "")
            'Me.DGV_Detail.Focus()
            'If DGV_Detail.RowCount > 0 Then
            '    Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.RowCount - 1).Cells("fSumCount")
            'End If
            'Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(0).Cells(2)
            'IsOutPut = True

            ''------------------------------------------------------------------------------------
            Dim mCount As Double
            mCount = Double.Parse(Me.DGV_Detail.CurrentRow.Cells("fSumCount").Value.ToString)
            Me.DGV_Detail.CurrentRow.Cells("SalePrice").Value = Format(GoodsSalePrice, "#0.00")
            Me.DGV_Detail.CurrentRow.Cells("fSumMoney").Value = Format((mCount * GoodsSalePrice), "#0.00")

            Me.DGV_Sum.Rows(0).Cells("fSumCount").Value = Format(mDatasetB.Tables(0).Compute("sum(fSumCount)", ""), "#0.00")
            'Me.DGV_Sum.Rows(0).Cells("fGoodsPrice").Value = Format(mDatasetB.Tables(0).Compute("sum(fGoodsPrice)", ""), "#0.00")
            Me.DGV_Sum.Rows(0).Cells("fSumMoney").Value = Format(mDatasetB.Tables(0).Compute("sum(fSumMoney)", ""), "#0.00")
            Me.txtSumDSIA.Text = Format(Format(mDatasetB.Tables(0).Compute("sum(fSumMoney)", ""), "#0.00") * (Me.NumericUpDown2.Value / 100), "#0.00")
            Me.txtBSI.Text = Format(Format(mDatasetB.Tables(0).Compute("sum(fSumMoney)", ""), "#0.00") - (Me.txtSumDSIA.Text), "#0.00")
            Me.txtFTAmount.Text = Format(mDatasetB.Tables(0).Compute("sum(fSumMoney)", ""), "#0.00")
            Me.txtActualAmount.Text = Format(Format(mDatasetB.Tables(0).Compute("sum(fSumMoney)", ""), "#0.00") * (Me.NumericUpDown2.Value / 100), "#0.00")

        End Try
    End Sub

    Private Function GetCurrentSalefPrice(ByVal BarCode As String) As Double
        Dim SalePrice As Double = 0.0
        Dim sql As String = " select top 1 Isnull(SalePrice,0)  from Goods_SalePrice where BarCode='*" & BarCode & "*' and Convert(varchar(10),ValidDate,21)<=Convert(varchar(10),getdate(),21) order by ValidDate desc "

        Dim oo As Object
        oo = Exec(sql, E_ExecType.ExecuteScalar)

        SalePrice = Val(oo & "")

        Return SalePrice
    End Function
    ''' <summary>
    ''' 添加主貨品
    ''' </summary>
    ''' <param name="BarCode"></param>
    ''' <param name="Rows"></param>
    ''' <param name="fGoodsSalePrice"></param>
    ''' <param name="mCount"></param>
    ''' <remarks></remarks>
    Private Sub AddBarCodeToTable(ByVal BarCode As String, ByVal Rows() As DataRow, ByVal fGoodsSalePrice As Double, ByVal mCount As Integer, Optional ByVal isSub As Boolean = False)
        Dim NewRow As DataRow = mDatasetB.Tables(0).NewRow
        NewRow("ItemNo") = Format(mDatasetB.Tables(0).Rows.Count + 1, "000")
        NewRow("Code") = Rows(0).Item("Code") & ""
        NewRow("CnName") = Rows(0).Item("CnName") & IIf(isSub = True, "(贈品)", "")
        NewRow("EnName") = Rows(0).Item("EnName")
        NewRow("fGoodsColor") = Rows(0).Item("fGoodsColor")
        NewRow("fGoodsSize") = Rows(0).Item("fGoodsSize")
        NewRow("fSumCount") = Format(mCount, "#0.00")
        NewRow("SalePrice") = Format(0, "#0.00")
        NewRow("fSumMoney") = Format(fGoodsSalePrice * mCount, "#0.00")
        NewRow("fGoodsBarCode") = "" & BarCode & ""
        mDatasetB.Tables(0).Rows.Add(NewRow)
        mDatasetB.AcceptChanges()
    End Sub

    Private Sub DGV_Detail_ColumnHeaderMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DGV_Detail.ColumnHeaderMouseClick

    End Sub

    Private Sub DGV_Detail_ColumnWidthChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles DGV_Detail.ColumnWidthChanged
        SetGridWidth(0)
    End Sub

    Private Sub DGV_Detail_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DGV_Detail.KeyDown

        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Select Case e.KeyCode
                    Case Keys.Delete
                        Dim CurrentRowNo As String = Me.DGV_Detail.CurrentRow.Cells("ItemNo").Value.ToString + ""
                        If CurrentRowNo.Length > 0 Then
                            Dim Rows() As DataRow = mDatasetB.Tables(0).Select("ItemNo='" & CurrentRowNo & "'")
                            If Rows.Length > 0 Then
                                mDatasetB.Tables(0).Rows.Remove(Rows(0))
                            End If
                            For i As Integer = 0 To mDatasetB.Tables(0).Rows.Count - 1
                                mDatasetB.Tables(0).Rows(i).Item("ItemNo") = Format(i + 1, "000")
                            Next
                            mDatasetB.AcceptChanges()
                            Me.DGV_Detail.DataSource = mDatasetB.Tables(0)
                        End If
                    Case Keys.Up

                    Case Keys.Down

                End Select
            End If
        Catch ex As Exception
            MsgBox("DGV_Detail_KeyDown:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub DGV_Master_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DGV_Master.KeyDown

        Dim ShopNo As String
        If Me.DGV_Master.RowCount > 0 Then
            ShopNo = Me.DGV_Master.CurrentRow.Cells("ShopNo").Value
        End If

        Select Case e.KeyCode
            Case Keys.Up
                If Me.DGV_Master.CurrentRow.Index - 1 < 0 Then
                    Exit Select
                End If
                If Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index - 1).Cells("fOrdeStatus").Value = "保存" Then
                    If ShopNo = PubCompanyName Then
                        MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = True And DeleteEnable = True
                        MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                    Else
                        MainForm.ToolStripCheck.Enabled = False
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = False
                        MainForm.ToolStripEdit.Enabled = False
                    End If
                    Me.BtnCancel.Enabled = False
                ElseIf Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index - 1).Cells("fOrdeStatus").Value = "核准" Then
                    MainForm.ToolStripCheck.Enabled = False
                    MainForm.ToolStripUnCheck.Enabled = True And UncheckEnable = True
                    MainForm.ToolStripComplete.Enabled = True And CompleteEnable = True
                    MainForm.ToolStripDelete.Enabled = False
                    MainForm.ToolStripEdit.Enabled = False
                    Me.BtnCancel.Enabled = True
                ElseIf Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index - 1).Cells("fOrdeStatus").Value = "反核准" Then
                    MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                    MainForm.ToolStripUnCheck.Enabled = False
                    MainForm.ToolStripComplete.Enabled = False
                    MainForm.ToolStripDelete.Enabled = False
                    MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                    Me.BtnCancel.Enabled = True
                ElseIf Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index - 1).Cells("fOrdeStatus").Value = "結案" Then
                    MainForm.ToolStripCheck.Enabled = False
                    MainForm.ToolStripUnCheck.Enabled = False
                    MainForm.ToolStripComplete.Enabled = False
                    MainForm.ToolStripDelete.Enabled = False
                    MainForm.ToolStripEdit.Enabled = False
                    Me.BtnCancel.Enabled = False
                End If
                If Me.DGV_Master.CurrentRow.Index - 1 = 0 Then
                    MainForm.ToolStripFirst.Enabled = False
                    MainForm.ToolStripNext.Enabled = True
                    MainForm.ToolStripPrivous.Enabled = False
                    MainForm.ToolStripLast.Enabled = True
                Else
                    MainForm.ToolStripFirst.Enabled = True
                    MainForm.ToolStripNext.Enabled = True
                    MainForm.ToolStripPrivous.Enabled = True
                    MainForm.ToolStripLast.Enabled = True
                End If
            Case Keys.Down
                If Me.DGV_Master.CurrentRow.Index + 1 >= Me.DGV_Master.RowCount Then
                    Exit Select
                End If
                If Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index + 1).Cells("fOrdeStatus").Value = "保存" Then
                    If ShopNo = PubCompanyName Then
                        MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = True And DeleteEnable = True
                        MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                    Else
                        MainForm.ToolStripCheck.Enabled = False
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = False
                        MainForm.ToolStripEdit.Enabled = False
                    End If
                    Me.BtnCancel.Enabled = False
                ElseIf Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index + 1).Cells("fOrdeStatus").Value = "核准" Then
                    MainForm.ToolStripCheck.Enabled = False
                    MainForm.ToolStripUnCheck.Enabled = True And UncheckEnable = True
                    MainForm.ToolStripComplete.Enabled = True And CompleteEnable = True
                    MainForm.ToolStripDelete.Enabled = False
                    MainForm.ToolStripEdit.Enabled = False
                    Me.BtnCancel.Enabled = True
                ElseIf Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index + 1).Cells("fOrdeStatus").Value = "反核准" Then
                    MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                    MainForm.ToolStripUnCheck.Enabled = False
                    MainForm.ToolStripComplete.Enabled = False
                    MainForm.ToolStripDelete.Enabled = False
                    MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                    Me.BtnCancel.Enabled = True
                ElseIf Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index + 1).Cells("fOrdeStatus").Value = "結案" Then
                    MainForm.ToolStripCheck.Enabled = False
                    MainForm.ToolStripUnCheck.Enabled = False
                    MainForm.ToolStripComplete.Enabled = False
                    MainForm.ToolStripDelete.Enabled = False
                    MainForm.ToolStripEdit.Enabled = False
                    Me.BtnCancel.Enabled = False
                End If
                If Me.DGV_Master.CurrentRow.Index = Me.DGV_Master.Rows.Count - 2 Then
                    MainForm.ToolStripFirst.Enabled = True
                    MainForm.ToolStripNext.Enabled = False
                    MainForm.ToolStripPrivous.Enabled = True
                    MainForm.ToolStripLast.Enabled = False
                Else
                    MainForm.ToolStripFirst.Enabled = True
                    MainForm.ToolStripNext.Enabled = True
                    MainForm.ToolStripPrivous.Enabled = True
                    MainForm.ToolStripLast.Enabled = True
                End If
        End Select
    End Sub

    Private Sub DGV_Master_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DGV_Master.RowPostPaint

        Dim mBrush As New System.Drawing.SolidBrush(Me.DGV_Master.RowHeadersDefaultCellStyle.ForeColor)

        e.Graphics.DrawString(Convert.ToString(e.RowIndex + 1, System.Globalization.CultureInfo.CurrentCulture), e.InheritedRowStyle.Font, mBrush, e.RowBounds.Location.X + 5, e.RowBounds.Location.Y + 4)

    End Sub

    Private Sub DGV_Master_Scroll(ByVal sender As Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles DGV_Master.Scroll
        Me.DGV_MasterSum.HorizontalScrollingOffset = Me.DGV_Master.HorizontalScrollingOffset
    End Sub

    Private Sub DGV_Detail_Scroll(ByVal sender As Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles DGV_Detail.Scroll
        'Me.DGV_Sum.FirstDisplayedScrollingColumnIndex = Me.DGV_Detail.FirstDisplayedScrollingColumnIndex
        Me.DGV_Sum.HorizontalScrollingOffset = Me.DGV_Detail.HorizontalScrollingOffset
    End Sub

    Private Sub CBCustomerNo_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CBCustomerNo.SelectedIndexChanged

        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If Me.CBCustomerNo.SelectedIndex = -1 Then Exit Sub
                Dim Rows() As DataRow = CustomerDS.Tables(0).Select("Code='" & Me.CBCustomerNo.SelectedValue & "'")
                If Rows.Length > 0 Then
                    Me.txtCustomer.Text = Rows(0).Item("Cnname") & ""
                    Me.txtCustomePhone.Text = Rows(0).Item("Phone1") & ""
                    Me.txtDliveraddress.Text = Rows(0).Item("CnAddress") & ""
                    Me.txtzhekou.Text = Rows(0).Item("ListB") & ""
                    If Rows(0).Item("ListB") & "" = "" Or Rows(0).Item("ListB") Is Nothing Then
                        Me.NumericUpDown1.Value = 100
                    Else
                        Me.NumericUpDown1.Value = Rows(0).Item("ListB") * 100
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox("CBCustomerNo_SelectedIndexChanged:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub cbmCustomeType_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbmCustomeType.SelectedIndexChanged

        Try
            Dim sql As String = ""
            Dim GetServerDate As String = ServerDate
            Dim CustomerType As String = Me.cbmCustomeType.SelectedValue.ToString
            CustomerDS = New DataSet
            If Me.cbmCustomeType.SelectedIndex = -1 Then
                Exit Sub
            End If
            sql = "select a.ID,a.Code,a.Cnname,a.LinkMan,a.CnAddress,a.FType,a.Phone1,a.FLevel,b.ListA,b.ListB from BSC_Customer a left join " & vbCrLf
            sql += "(select b.* from dbo.BSC_OtherDefineA a inner join BSC_OtherDefineB b on a.ID=b.ItemNo where a.ItemCode='MemberLevel') b " & vbCrLf
            sql += "on a.FLevel=b.ListCode where a.Status=1 and Ftype='" & CustomerType & "'  and convert(nvarchar(10),a.stopdate,21)>='" & ServerDate & "';" & vbCrLf
            sql += " SELECT isnull(FCName,'')as FCName,isnull(fAddress,'')as fAddress,isnull(fPhone,'')as fPhone,isnull(fFax,'')as fFax FROM DBO.BSC_DEPT WHERE FDEFINE= 0 AND ID = "
            sql += " (SELECT FPARENTID FROM BSC_DEPT WHERE FCODE = '" & PubCompanyCode & "' ) "

            CustomerDS = ReturnDataset(sql)

            Me.CBCustomerNo.DisplayMember = "Code"
            Me.CBCustomerNo.ValueMember = "Code"
            Me.CBCustomerNo.DataSource = CustomerDS.Tables(0)
            Me.CBCustomerNo.SelectedIndex = -1
            If CustomerType = "Retail" Then
                Me.TabControl2.TabPages.Clear()
                If Not Me.TabControl2.TabPages.Contains(Me.TabPage3) Then
                    Me.TabControl2.TabPages.Add(Me.TabPage3)
                End If
                Me.GroupBox2.Visible = False
                'Me.CBSelMode.SelectedIndex = -1
                'Me.CBSelMode.Enabled = False 
                'Me.CBSelMode.Visible = False
                'Me.DGV_PayMode.Visible = True
                'Label36.Visible = False
            Else
                Me.TabControl2.TabPages.Clear()
                If Not Me.TabControl2.TabPages.Contains(Me.TabPage4) Then
                    Me.TabControl2.TabPages.Add(Me.TabPage4)
                End If
                Me.GroupBox2.Visible = True
                Me.txtFCName.Text = CustomerDS.Tables(1).Rows(0)("FCName")
                Me.txtfAddress.Text = CustomerDS.Tables(1).Rows(0)("fAddress")
                Me.txtfPhone.Text = CustomerDS.Tables(1).Rows(0)("fPhone")
                Me.txtfFax.Text = CustomerDS.Tables(1).Rows(0)("fFax")
                'Me.CBSelMode.Visible = True& ""
                'Me.CBSelMode.Enabled = True
                'Label36.Visible = True
                'Me.DGV_PayMode.Visible = False
            End If
        Catch ex As Exception
            MsgBox("cbmCustomeType_SelectedIndexChanged:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub btnPrint_Click()

        Try
            Me.DGV_Detail.Columns("fRemark").Visible = False
            Me.DGV_Detail.Columns("fGoodsSize").Visible = False
            Dim mPrint As New fhtPrint.fhtPrint.fhtPrint
            Dim FilePath As String = Application.StartupPath + "\pic\DSC.jpg"
            mPrint.TitleTopHeigth = 100
            mPrint.Title = PubCompanyName
            mPrint.OrdeType = "訂金收據"
            mPrint.ShopAddress = ""
            mPrint.HeaderX1 = "合同編號:" & LabOrdingNo.Text
            mPrint.HeaderX2 = "手寫單號:" & Me.txtWriteNo.Text
            mPrint.HeaderX3 = "發票編號:" & "AMI00064717"
            mPrint.HeaderX4 = "銷售日期:" & Me.txtSaleDate.Value
            mPrint.HeaderY1 = "送貨類型:" & Me.CBDeliverMode.Text
            mPrint.HeaderY2 = "單據類型:" & Me.cmbDept.Text
            mPrint.HeaderY3 = "打印日期:" & ServerDate
            mPrint.CustomeName = "客戶名稱:" & Me.txtCustomer.Text
            mPrint.LinkMan = "收貨人:" & Me.txtReciveman.Text
            mPrint.LinkPhone = "聯系電話:" & Me.txtCustomePhone.Text
            mPrint.DeliverDate = "送貨日期:" & Me.DateTimePicker1.Value
            mPrint.DeliverAddress = "送貨地址:" & Me.txtDliveraddress.Text
            If File.Exists(FilePath) Then
                mPrint.Image = Image.FromFile(FilePath)
            End If
            mPrint.MyDataGridView = Me.DGV_Detail
            mPrint.SumMoney1 = "總金額:" & Format(mDatasetB.Tables(0).Compute("sum(fSumMoney)", ""), "#0.00")
            mPrint.SumMoney2 = "已收訂金:" & Me.txtSumDSI.Text
            mPrint.SumMoney3 = "尚欠:" & Me.txtBSI.Text
            mPrint.PageFooter = "收銀員:" & PubUserCode & Space(15) & "營業員:" & Me.CBSaleman.Text
            'mPrint.PageRigthFooter = Me.LabOrdingNo.Text
            mPrint.PrintPreviewDialog()
            Me.DGV_Detail.Columns("fRemark").Visible = True
            Me.DGV_Detail.Columns("fGoodsSize").Visible = True
        Catch ex As Exception
            MsgBox("btnPrint_Click:" & ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub ComBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComBox.SelectedIndexChanged

        Try
            Dim sql As String = ""
            Dim RateType As String = ""
            Dim m_Ds As New DataSet
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                sql = "select * from BSC_SystemProfile where FKey='RateType'"
                m_Ds = ReturnDataset(sql)
                If m_Ds.Tables(0).Rows.Count > 0 Then
                    Dim F_Currency As String = Me.cmbStandardMoney.SelectedValue.ToString
                    Dim T_Currency As String = Me.ComBox.SelectedValue.ToString
                    Dim Time_Currency As String = ServerDate
                    RateType = m_Ds.Tables(0).Rows(0).Item("FValue") & ""
                    sql = "select dbo.GetRate('" & RateType & "','" & Time_Currency & "','" & F_Currency & "','" & T_Currency & "')"
                    m_Ds = ReturnDataset(sql)
                    If m_Ds.Tables(0).Rows.Count > 0 Then
                        If m_Ds.Tables(0).Rows(0).Item(0) & "" = "-1" Then
                            MsgBox("漚率為空，請維護漚率表！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                            Exit Sub
                        End If
                        Me.DGV_PayMode.CurrentRow.Cells("Rate").Value = Convert.ToDouble(m_Ds.Tables(0).Rows(0).Item(0))
                    Else
                        MsgBox("漚率為空，請維護漚率表！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    End If
                    Me.DGV_PayMode.CurrentRow.Cells("Currency").Value = ComBox.Text
                    Me.DGV_PayMode.CurrentRow.Cells("Currency").Tag = ComBox.SelectedValue
                End If
            End If

        Catch ex As Exception
            MsgBox("ComBox_SelectedIndexChanged:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub DGV_PayMode_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_PayMode.CellValueChanged

        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If e.ColumnIndex = 3 Then
                    Dim CurrentMoney As Double = Convert.ToDouble(Me.DGV_PayMode.CurrentRow.Cells("payMoney_f").Value)
                    Dim CurrentRate As Double = Convert.ToDouble(Me.DGV_PayMode.CurrentRow.Cells("Rate").Value)
                    Me.DGV_PayMode.CurrentRow.Cells("payMoney_t").Value = CurrentMoney * CurrentRate
                    Me.txtSumDSI.Text = Format(mDatasetC.Tables(0).Compute("sum(payMoney_t)", ""), "#0.00")
                    Me.txtBalanse.Text = Val(Me.txtSumDSI.Text) - Val(Me.txtActualAmount.Text)
                ElseIf e.ColumnIndex = 2 Then
                    Dim ifhave As Boolean = False
                    Dim row As DataGridViewRow = Me.DGV_PayMode.Rows(e.RowIndex)
                    Dim s As String = row.Cells(1).Value
                    If s.Equals("Gift", StringComparison.InvariantCultureIgnoreCase) Then
                        If row.Cells(2).Value Is Nothing OrElse TypeOf row.Cells(2).Value Is System.DBNull Then
                            row.Cells(3).Value = 0
                            Exit Sub
                        End If
                        Dim cardnum As String = row.Cells(2).Value
                        If Not String.IsNullOrEmpty(cardnum) Then
                            'chazhao shifou shiyong 
                            Dim sql As String = " select * from dbo.BSC_Gift where Convert(varchar(10),getdate(),121) " + _
                            " between Convert(varchar(10), StartDate, 21) And Convert(varchar(10), EndDate, 21) " + _
                            " and Status=0 and Num='" + cardnum + "'"
                            Dim tab As DataTable = Exec(sql, E_ExecType.DataTable)
                            If tab.Rows.Count = 0 Then
                                row.Cells(3).Value = 0
                            Else
                                ifhave = True
                                row.Cells(3).Value = Val(tab.Rows(0)("FaceAmount"))
                            End If
                        Else
                            row.Cells(3).Value = 0
                        End If
                        If ifhave = False Then
                            MessageBox.Show("禮券(" + cardnum + ")過期或不存在")
                        End If

                    End If
                End If
            End If

        Catch ex As Exception
            MsgBox("ComBox_SelectedIndexChanged:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub DGV_PayMode_ColumnWidthChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles DGV_PayMode.ColumnWidthChanged
        ComBox.Visible = False
    End Sub

    Private Sub DGV_PayMode_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGV_PayMode.CurrentCellChanged

        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If Me.DGV_PayMode.CurrentCell Is Nothing Then Exit Sub

                If Me.DGV_PayMode.CurrentCell.ColumnIndex = 4 Then
                    Dim Rect As Rectangle = Me.DGV_PayMode.GetCellDisplayRectangle(Me.DGV_PayMode.CurrentCell.ColumnIndex, Me.DGV_PayMode.CurrentCell.RowIndex, False)
                    Dim CurrencyValue As String = Me.DGV_PayMode.CurrentCell.Value.ToString
                    ComBox.Left = Rect.Left
                    ComBox.Top = Rect.Top
                    ComBox.Width = Rect.Width
                    ComBox.Height = 100
                    ComBox.Visible = True
                Else
                    ComBox.Visible = False
                End If
            End If
        Catch ex As Exception
            MsgBox("DGV_PayMode_CurrentCellChanged:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub DGV_PayMode_Scroll(ByVal sender As Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles DGV_PayMode.Scroll
        ComBox.Visible = False
    End Sub

    Private Sub txtActualAmount_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtActualAmount.TextChanged
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd OrElse ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Me.txtBSI.Text = Val(Me.txtFTAmount.Text) - Val(Me.txtActualAmount.Text)
                'txtBalanse.Text = Val(txtSumDSI.Text) - Val(txtActualAmount.Text)
                'If (Val(txtBalanse.Text) < 0) Then
                '    MessageBox.Show("請檢察實收訂金或者實收金額是否正確。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Question)
                'End If
                If Val(Me.txtSumDSI.Text) > 0 Then
                    txtBalanse.Text = Val(txtSumDSI.Text) - Val(txtActualAmount.Text)
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message + ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub DGV_Master_Sorted(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGV_Master.Sorted

        If mDatasetA.Tables(0).Rows.Count > 0 Then
            SetGridRowBackColor(Me.DGV_Master, mDatasetA)
        End If
    End Sub

    Private Sub CBDeliverMode_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CBDeliverMode.SelectedIndexChanged

        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If Me.CBDeliverMode.SelectedIndex = 0 Then
                    Me.ComboBox1.Enabled = True
                ElseIf Me.CBDeliverMode.SelectedIndex = 2 Then
                    If UncheckEnable = False Then
                        MsgBox("對不起，你無權使用此項！", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        Me.CBDeliverMode.SelectedIndex = -1
                    End If
                Else
                    Me.ComboBox1.Enabled = False
                End If
            End If

        Catch ex As Exception
            MsgBox("CBDeliverMode_SelectedIndexChanged:" & ex.Message, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub BtnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnCancel.Click

        Dim sql As String = ""
        Dim fSaleOrdeNo As String = ""
        Try
            If Me.DGV_Master.RowCount <= 0 Then Exit Sub
            fSaleOrdeNo = Me.DGV_Master.CurrentRow.Cells("fSaleOrdeNo").Value
            If MsgBox("確認取消該單據嗎？", MsgBoxStyle.Question + MsgBoxStyle.OkCancel, Msg.CompanyName) = MsgBoxResult.Ok Then
                sql = "Update Sal_SaleOrdeA Set fOrdeStatus='D' where fSaleOrdeNo='" & fSaleOrdeNo & "'"
                ReturnObject(sql)
                MsgBox("操作成功！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            End If
        Catch ex As Exception
            MsgBox("BtnCancel_Click:" & ex.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub txtOrdeType_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtOrdeType.DoubleClick

        Me.TreeView1.Focus()
        Me.TreeView1.Select()

        If Me.Panel5.Visible = False Then
            Me.Panel5.Visible = True
        Else
            Me.Panel5.Visible = False
        End If
    End Sub

    Private Sub TreeView1_AfterCheck(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterCheck

        Try
            If Not e.Node Is Nothing Then

                If e.Node.Checked = True Then
                    If e.Node.Tag = "All" Then
                        For Each mNode As TreeNode In e.Node.Nodes
                            mNode.Checked = True
                        Next
                    End If
                    Me.txtOrdeType.Text += e.Node.Text & ","
                    If Not Me.LabTag.Text.Contains(e.Node.Tag & ",") Then
                        Me.LabTag.Text += e.Node.Tag & ","
                    End If
                    Me.txtOrdeType.Text = Me.txtOrdeType.Text.Replace("全部,", "")
                    Me.LabTag.Text = Me.LabTag.Text.Replace("All,", "")
                Else
                    If e.Node.Tag = "All" Then
                        For Each mNode As TreeNode In e.Node.Nodes
                            mNode.Checked = False
                        Next
                    End If
                    If Me.LabTag.Text.Length > 0 Then
                        If Me.LabTag.Text.Contains(e.Node.Tag) Then
                            If Me.txtOrdeType.Text.Contains(e.Node.Text + ",") Then
                                Me.txtOrdeType.Text = Me.txtOrdeType.Text.Remove(Me.txtOrdeType.Text.IndexOf(e.Node.Text & ","), Len(e.Node.Text & ","))
                            End If
                            Me.LabTag.Text = Me.LabTag.Text.Remove(Me.LabTag.Text.IndexOf(e.Node.Tag & ","), Len(e.Node.Tag & ","))
                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox("TreeView1_AfterCheck:" & ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub TreeView1_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TreeView1.LostFocus
        Me.Panel5.Visible = False
    End Sub

    Private Sub DGV_Master_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles DGV_Master.Paint
        FormatDgrd(DGV_Master, "fOrdeStatus")
    End Sub

    Private Sub BtnPathOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnPathOpen.Click
        Try

            Dim Pathstr As String
            '讀文件()
            With Me.OpenFileDialog1
                .FileName = ""
                .Filter = ""
                .Multiselect = False
                .Title = "選擇打開的文件"
            End With

            If Me.OpenFileDialog1.ShowDialog = DialogResult.OK Then
                Pathstr = Me.OpenFileDialog1.FileName
            End If
            If Pathstr = "" Then
                Exit Sub
            End If
            Me.TxtPath.Text = Pathstr
        Catch ex As Exception
            MsgBox(ex.Message, Msg.CompanyName)
        End Try

    End Sub

#End Region

    Private Sub DeliverType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeliverType.SelectedIndexChanged

    End Sub
    Private Sub OrderCustomerType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OrderCustomerType.SelectedIndexChanged

    End Sub
End Class
